对于Linux和Windows文件目录位置配置
发表于更新于
字数总计:384阅读时长:1分钟阅读量: 北京
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")) { String path = System.getProperty("user.dir"); filePath = path + "\\src\\main\\resources\\static\\" + datePath + "\\" + fileType; } else { 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);
|