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
- import java.io.File;
- public class Test {
- public static void main(String[] args) throws Exception {
- delFolder("E:/test");
- }
- /***
- * 删除指定文件夹下所有文件
- *
- * @param path 文件夹完整绝对路径
- * @return
- */
- public static boolean delAllFile(String path) {
- boolean flag = false;
- File file = new File(path);
- if (!file.exists()) {
- return flag;
- }
- if (!file.isDirectory()) {
- return flag;
- }
- String[] tempList = file.list();
- File temp = null;
- for (int i = 0; i < tempList.length; i++) {
- if (path.endsWith(File.separator)) {
- temp = new File(path + tempList[i]);
- } else {
- temp = new File(path + File.separator + tempList[i]);
- }
- if (temp.isFile()) {
- temp.delete();
- }
- if (temp.isDirectory()) {
- delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
- delFolder(path + "/" + tempList[i]);// 再删除空文件夹
- flag = true;
- }
- }
- return flag;
- }
- /***
- * 删除文件夹
- *
- * @param folderPath文件夹完整绝对路径
- */
- public static void delFolder(String folderPath) {
- try {
- delAllFile(folderPath); // 删除完里面所有内容
- String filePath = folderPath;
- filePath = filePath.toString();
- java.io.File myFilePath = new java.io.File(filePath);
- myFilePath.delete(); // 删除空文件夹
- } catch (Exception e) {
- e.printStackTrace();
- }
- }