我创建了一些代码来删除文件夹中的所有文件,问题是虽然这很好,但我希望能够删除目录中的所有文件但保持文件夹完整,所以我不必进入每个文件夹并删除其中的文件,这是我当前的代码:
@ViewScoped
@ManagedBean
public class Delete {
public void DeleteFiles() throws IOException {
System.out.println("Called deleteFiles");
File file = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/up617648/");
String[] myFiles;
if (file.isDirectory()) {
myFiles = file.list();
for (int i = 0; i < myFiles.length; i++) {
File myFile = new File(file, myFiles[i]);
System.out.println(myFile);
myFile.delete();
}
DeleteFiles2();
}
}
public void DeleteFiles2() throws IOException {
System.out.println("Called deleteFiles2");
File file = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/Uploaded/up617648/");
String[] myFiles;
if (file.isDirectory()) {
myFiles = file.list();
for (int i = 0; i < myFiles.length; i++) {
File myFile = new File(file, myFiles[i]);
System.out.println(myFile);
myFile.delete();
}
}
}
}
我怎样才能修改我的代码来实现这个目标?
编辑 :
我已将代码更改为:
@ViewScoped
@ManagedBean
public class Delete {
public void DeleteFiles() throws IOException {
System.out.println("Called deleteFiles");
File file = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/");
String[] myFiles;
if (file.isDirectory()) {
myFiles = file.list();
for (int i = 0; i < myFiles.length; i++) {
File myFile = new File(file, myFiles[i]);
System.out.println(myFile);
if (!myFile.isDirectory()) {
myFile.delete();
}
}
DeleteFiles2();
}
}
虽然这确实调用了所有文件夹,但这是我的控制台:
INFO: Called deleteFiles
INFO: D:\Documents\NetBeansProjects\printing~subversion\fileupload\web\resources\pdf\cam01342
INFO: D:\Documents\NetBeansProjects\printing~subversion\fileupload\web\resources\pdf\geg00061
INFO: D:\Documents\NetBeansProjects\printing~subversion\fileupload\web\resources\pdf\null
INFO: D:\Documents\NetBeansProjects\printing~subversion\fileupload\web\resources\pdf\up617648
INFO: D:\Documents\NetBeansProjects\printing~subversion\fileupload\web\resources\pdf\up626088
INFO: Called deleteFiles2
Tt 不会删除这些文件夹中的文件,我该怎么做?
编辑 3:使用递归我现在收到堆栈溢出错误。
这是我的代码:
public void DeleteFiles() {
File file = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/");
System.out.println("Called deleteFiles");
if (file.isDirectory()) {
for (File f : file.listFiles()) {
DeleteFiles();
}
} else {
file.delete();
}
}