1 前言

如果在Windows环境下进行本地开发,在Linux环境下进行服务运行,但两者文件管理的目录表达并不相同,因此在开发时,需要考虑目录的格式是否正确。

Windows下的文件位置目录示例:

1
String path = "C:\\Users\\ly\\Desktop\\codes\\pdf\\src\\main\\resources\\static\\2022-12-04\\image\\1.png";

Linux下的文件位置目录示例:

1
String path = "/usr/local/backend/pdf/2022-12-04/image/1.png"

2 getFilePath()方法定义

此方法根据文件类型获取需要存放的目录位置,如fileType为image时,在Windows和Linux环境下分别输出:

C:\Users\ly\Desktop\codes\pdf\src\main\resources\static\2022-12-04\image

/usr/local/backend/pdf/2022-12-04/image

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@SneakyThrows
public static String getFilePath(String fileType) {
String os = System.getProperty("os.name");
System.out.println("os:" + os);
String filePath;

// 设置 日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String datePath = sdf.format(new Date());

if (os.toLowerCase().startsWith("win")) {
// windows系统
String path = System.getProperty("user.dir"); //获取项目相对路径
filePath = path + "\\src\\main\\resources\\static\\" + datePath + "\\" + fileType;
} else {
// linux系统
// 如果是linux环境下,目录为jar包同级目录
File rootPath = new File(ResourceUtils.getURL("classpath:").getPath());
if (!rootPath.exists()) {
rootPath = new File("");
}
filePath = rootPath.getAbsolutePath() + "/" + datePath + "/" + fileType;
}
System.out.println(fileType + "Path:" + filePath);
// 判断该文件夹是否存在,不存在则创建
if (!new File(filePath).exists()) {
new File(filePath).mkdirs();
}
return filePath;
}

3 调用示例

1
2
3
4
5
String imagePath = getFilePath("image");
// 业务代码...
File file = new File(imagePath, multipartFile.getOriginalFilename());
multipartFile.transferTo(file);
// 业务代码...