一、所用工具
傳統刪除是利用IO流,本文利用NIO流實現。
二、常見幾種方法
1.傳統IO流
代碼如下(示例):
//調用
File file = new File("E:/河南省鄉(xiāng)鎮(zhèn)點/GIS/");
deleteFile(file);
//刪除文件夾及其文件
public static void deleteFile(File file){
//獲取目錄下子文件
File[] files = file.listFiles();
//遍歷該目錄下的文件對象
for (File f : files) {
//打印文件名
System.out.println("文件名:" + f.getName());
//文件刪除
f.delete();
}
boolean delete = file.delete();
System.out.println(delete);
}
2.強制刪除(如若一次刪除失敗,進行多次強制刪除即可)
代碼如下(示例):
//調用
File file = new File("E:/河南省鄉(xiāng)鎮(zhèn)點/GIS/");
forceDelete(file);
//強制刪除
public static boolean forceDelete(File file) {
boolean result = file.delete();
int tryCount = 0;
while (!result && tryCount++ < 10) {
System.gc(); //回收資源
result = file.delete();
}
return result;
}
3.利用NIO流
代碼如下(示例):文章來源:http://www.zghlxwxcb.cn/news/detail-686048.html
Path path= Paths.get("E:\\河南省鄉(xiāng)鎮(zhèn)點\\GIS");
Files.walkFileTree(path,new SimpleFileVisitor<>(){
//遍歷刪除文件
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
//遍歷刪除目錄
public FileVisitResult postVisitDirectory(Path dir,IOException exc) throws IOException{
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
總結
利用NIO流的好處:
1.如果刪除失敗,可以給出錯誤的具體原因;
2.代碼不多,效率高。文章來源地址http://www.zghlxwxcb.cn/news/detail-686048.html
到了這里,關于java刪除文件或目錄的三種方法的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!