我正在尝试使用for循环删除文件。
for(int i = 0; i < 3; i++) {
String pathName = "test" + i + ".csv";
boolean success = (new File(pathName)).delete();
}
但是此代码仅删除第一个文件,而不删除其他文件。
这对我有用。也许文件所在的路径不正确。
for(int i = 1; i <= 3; i++) {
boolean success = (new File("C:\\Users\\Suppada-Aide\\Desktop\\test"+i+".txt")).delete();
System.out.println(success);
}
只需使用此代码:
public class Example {
public static void main(String args[]) {
// set the folder path
File folder = new File("C:\\Users\\Desktop\\New Folder");
// call this method
deleteFiles(folder);
}
// this method recursively goes into the folder and delete all the files.
private static void deleteFiles(File folder) {
for (File file : folder.listFiles()) {
// check whether the file is a directory or not.
if (file.isDirectory()) {
deleteFiles(file);
}
// check whether file starts with "test" or not.
// if matched, then file is deleted or not.
if (file.getName().startsWith("test")) {
if (file.delete()) {
System.out.println("File deleted");
}
}
}
}
}
输出:
File deleted
File deleted
只需根据您的需要修改代码。
希望对您有帮助。
:)