在Java中,我想删除包含文件和文件夹的文件夹中存在的所有内容。
public void startDeleting(String path) {
List<String> filesList = new ArrayList<String>();
List<String> folderList = new ArrayList<String>();
fetchCompleteList(filesList, folderList, path);
for(String filePath : filesList) {
File tempFile = new File(filePath);
tempFile.delete();
}
for(String filePath : folderList) {
File tempFile = new File(filePath);
tempFile.delete();
}
}
private void fetchCompleteList(List<String> filesList,
List<String> folderList, String path) {
File file = new File(path);
File[] listOfFile = file.listFiles();
for(File tempFile : listOfFile) {
if(tempFile.isDirectory()) {
folderList.add(tempFile.getAbsolutePath());
fetchCompleteList(filesList,
folderList, tempFile.getAbsolutePath());
} else {
filesList.add(tempFile.getAbsolutePath());
}
}
}
此代码不起作用,执行此操作的最佳方法是什么?
如果你使用Apache 公共 IO http://commons.apache.org/io这是一行:
FileUtils.deleteDirectory(dir);
See FileUtils.deleteDirectory() http://commons.apache.org/proper/commons-io///apidocs/org/apache/commons/io/FileUtils.html#deleteDirectory%28java.io.File%29
Guava http://code.google.com/p/guava-libraries used to support similar functionality:
Files.deleteRecursively(dir);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)