我需要删除的文件夹是从我的程序创建的文件夹。每台电脑上的目录都不一样,所以我使用的文件夹代码是
userprofile+"\\Downloads\\Software_Tokens"
会有文件,所以我想我需要递归删除它。我在这里看了一些样品,但它从不接受我的道路。该路径在代码中作为环境变量正常工作,因为我为它添加了代码
static String userprofile = System.getenv("USERPROFILE");
所以有人可以告诉我路径插入的代码吗?
答案 0 :(得分:1)
如果您的目录不为空,则可以使用Apache Commons IO API的方法deleteDirectory(File file):
String toDelete = userprofile + File.separator + "Downloads" +
File.separator + "Software_Tokens";
FileUtils.deleteDirectory(new File(toDelete));
请注意与系统相关的/
或\
并改为使用File.separator
。
答案 1 :(得分:0)
如果你不想使用apache库!你可以递归地做。
String directory = userprofile + File.separator + "Downloads" + File.separator + "Software_Tokens";
if (!directory.exists()) {
System.out.println("Directory does not exist.");
System.exit(0);
} else {
try {
delete(directory);
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
System.out.println("Done");
}
public static void delete(File file)
throws IOException {
if (file.isDirectory()) {
//directory is empty, then delete it
if (file.list().length == 0) {
file.delete();
System.out.println("Directory is deleted : " + file.getAbsolutePath());
} else {
//list all the directory contents
String files[] = file.list();
for (String temp: files) {
//construct the file structure
File fileDelete = new File(file, temp);
//recursive delete
delete(fileDelete);
}
//check the directory again, if empty then delete it
if (file.list().length == 0) {
file.delete();
System.out.println("Directory is deleted : " + file.getAbsolutePath());
}
}
} else {
//if file, then delete it
file.delete();
System.out.println("File is deleted : " + file.getAbsolutePath());
}