删除文件
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| package com.rc;
import java.io.File;
public class DeleteFileJava {
public static void main(String[] args) { File file = new File("tmp/tmp2/file.txt"); if(file.delete()){ System.out.println("tmp/tmp2/file.txt File deleted"); }else System.out.println("File tmp/tmp2/file.txt doesn't exist");
file = new File("file.txt"); if(file.delete()){ System.out.println("file.txt File deleted from Project root directory"); }else System.out.println("File file.txt doesn't exist in the project root directory");
file = new File("temp/file.txt"); if(file.delete()){ System.out.println("temp/file.txt File deleted from Project root directory"); }else System.out.println("File temp/file.txt doesn't exist in the project root directory");
file = new File("temp"); if(file.delete()){ System.out.println("temp directory deleted from Project root directory"); }else System.out.println("temp directory doesn't exist or not empty in the project root directory");
file = new File("D:/user/maxsu/project"); if(file.delete()){ System.out.println("D:/user/maxsu/project directory deleted from Project root directory"); }else System.out.println("D:/user/maxsu/project directory doesn't exist or not empty"); }
}
|
delete方法不会抛出IOException异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import java.io.File;
public class JavaDeleteDirectory {
public static void main(String[] args) { File dir = new File("D:/worksp/java/log");
if(dir.isDirectory() == false) { System.out.println("Not a directory. Do nothing"); return; } File[] listFiles = dir.listFiles(); for(File file : listFiles){ System.out.println("Deleting "+file.getName()); file.delete(); } System.out.println("Deleting Directory. Success = "+dir.delete());
}
}
|