Java Program to delete files for the file names starting with "Test-"
package fileio;
import java.io.File;
import java.io.FilenameFilter;
public class DeleteFileName {
public static void main(String[] args) {
try {
final String filePrefix = "Test-";
String filesDir = System.getProperty("user.dir") + "\\src\\fileio";
File dir = new File(filesDir);
File[] foundFiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(filePrefix);
}
});
System.out.println("Number of files found : " + foundFiles.length);
System.out.println("");
for (File file : foundFiles) {
try {
if (file.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed, unable to delete the file.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
package fileio;
import java.io.File;
import java.io.FilenameFilter;
public class DeleteFileName {
public static void main(String[] args) {
try {
final String filePrefix = "Test-";
String filesDir = System.getProperty("user.dir") + "\\src\\fileio";
File dir = new File(filesDir);
File[] foundFiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(filePrefix);
}
});
System.out.println("Number of files found : " + foundFiles.length);
System.out.println("");
for (File file : foundFiles) {
try {
if (file.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed, unable to delete the file.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Executing the above java program:
No comments:
Post a Comment