话不多说,先上代码~~
/**
* 删除服务上的文件
* @param filePath 路径
* @param fileName 文件名
* @return
*/
@PostMapping("/deleteServerFile")
@ResponseBody
public static boolean deleteServerFile(String filePath){
boolean delete_flag = false;
File file = new File(filePath);
if (!file.exists()) {
return delete_flag;
}
try{
delete_flag = file.delete();
}catch (Exception e){
e.printStackTrace();
}
return delete_flag;
}
在Windows下的路径分隔符和Linux下的路径分隔符是不一样的,当直接使用绝对路径时,跨平台会暴出“No such file or diretory”的异常。
比如说要在temp目录下建立一个test.txt文件,在Windows下应该这么写:
File file1 = new File ("C:\tmp\test.txt");
在linux下则是这样的:
File file2 = new File ("/tmp/test.txt");
如果要考虑跨平台,则最好是这么写:
File myFile = new File("C:" + File.separator + "tmp" + File.separator, "test.txt");
注意:1.如果是要删除Linux服务器上面的文件,必须要把项目先打包到Linux服务器上,然后看Linux上面的日志记录,如果是使用File.separator在本地查看日志的话,路径分隔符就是 "\" 它了
2.默认路径是工程的根目录
我的待删除文件的路径如下图:
所以我的filePath就是
File file = new File(File.separator +"home" + File.separator + "ruoyi" + File.separator + "uploadPath" + File.separator + "upload"+ File.separator, "9e38014f8aaf99e0d1c509903ec4cd79.png");