java 删除指定文件夹 以及文件下下面的所有文件

java 删除指定文件夹 以及文件下下面的所有文件

2017年08月28日 00:24:20

阅读数:3700

文件路径的分隔符在windows系统和linux系统中是不一样。
比如说要在temp目录下建立一个test.txt文件,在Windows下应该这么写:
File file1 = new File (“C:\tmp\test.txt”);
在Linux下则是这样的:
File file2 = new File (“/tmp/test.txt”);
而我刚开始就是按照File file1 = new File (“C:\tmp\test.txt”);这种方式写的,在
Windows下没有问题,但是将工程部署在服务器上时,就出问题了。服务器是linux系统,所
以这时文件路径就出错了。后来将分隔符用File.separator 代替,ok,问题解决了。下边介
绍下File.separator 。
如果要考虑跨平台,则最好是这么写:
File myFile = new File(“C:” + File.separator + “tmp” + File.separator, “test.txt”);

File类有几个类似separator的静态字段,都是与系统相关的,在编程时应尽量使用。

[java] view plain copy

  1. import java.io.File;  
  2.   
  3. public class Test {  
  4.   
  5.     public static void main(String[] args) throws Exception {  
  6.         delFolder("E:/test");  
  7.     }  
  8.     /*** 
  9.      * 删除指定文件夹下所有文件 
  10.      *  
  11.      * @param path 文件夹完整绝对路径 
  12.      * @return 
  13.      */  
  14.     public static  boolean delAllFile(String path) {  
  15.         boolean flag = false;  
  16.         File file = new File(path);  
  17.         if (!file.exists()) {  
  18.             return flag;  
  19.         }  
  20.         if (!file.isDirectory()) {  
  21.             return flag;  
  22.         }  
  23.         String[] tempList = file.list();  
  24.         File temp = null;  
  25.         for (int i = 0; i < tempList.length; i++) {  
  26.             if (path.endsWith(File.separator)) {  
  27.                 temp = new File(path + tempList[i]);  
  28.             } else {  
  29.                 temp = new File(path + File.separator + tempList[i]);  
  30.             }  
  31.             if (temp.isFile()) {  
  32.                 temp.delete();  
  33.             }  
  34.             if (temp.isDirectory()) {  
  35.                 delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件  
  36.                 delFolder(path + "/" + tempList[i]);// 再删除空文件夹  
  37.                 flag = true;  
  38.             }  
  39.         }  
  40.         return flag;  
  41.     }  
  42.       
  43.     /*** 
  44.      * 删除文件夹 
  45.      *  
  46.      * @param folderPath文件夹完整绝对路径 
  47.      */  
  48.     public  static void delFolder(String folderPath) {  
  49.         try {  
  50.             delAllFile(folderPath); // 删除完里面所有内容  
  51.             String filePath = folderPath;  
  52.             filePath = filePath.toString();  
  53.             java.io.File myFilePath = new java.io.File(filePath);  
  54.             myFilePath.delete(); // 删除空文件夹  
  55.         } catch (Exception e) {  
  56.             e.printStackTrace();  
  57.         }  
  58.     }  

猜你喜欢

转载自blog.csdn.net/evilcry2012/article/details/81808532
今日推荐