我想删除ABC目录下的所有文件。
当我尝试FileUtils.deleteDirectory(新文件(“C:/test/ABC/”));它还会删除文件夹ABC。
是否有一个一行解决方案,我可以删除目录内的文件,但不是目录?
我想删除ABC目录下的所有文件。
当我尝试FileUtils.deleteDirectory(新文件(“C:/test/ABC/”));它还会删除文件夹ABC。
是否有一个一行解决方案,我可以删除目录内的文件,但不是目录?
当前回答
我认为这是可行的(基于非线性水果之前的答案):
Files.walk(Paths.get("C:/test/ABC/"))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.filter(item -> !item.getPath().equals("C:/test/ABC/"))
.forEach(File::delete);
干杯!
其他回答
或者在Java 8中使用这个:
try {
Files.newDirectoryStream( directory ).forEach( file -> {
try { Files.delete( file ); }
catch ( IOException e ) { throw new UncheckedIOException(e); }
} );
}
catch ( IOException e ) {
e.printStackTrace();
}
很遗憾异常处理是如此庞大,否则它将是一行程序…
package com;
import java.io.File;
public class Delete {
public static void main(String[] args) {
String files;
File file = new File("D:\\del\\yc\\gh");
File[] listOfFiles = file.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
System.out.println(files);
if(!files.equalsIgnoreCase("Scan.pdf"))
{
boolean issuccess=new File(listOfFiles[i].toString()).delete();
System.err.println("Deletion Success "+issuccess);
}
}
}
}
}
如果你想删除所有文件删除
if(!files.equalsIgnoreCase("Scan.pdf"))
语句是可以的。
我认为这是可行的(基于非线性水果之前的答案):
Files.walk(Paths.get("C:/test/ABC/"))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.filter(item -> !item.getPath().equals("C:/test/ABC/"))
.forEach(File::delete);
干杯!
public class DeleteFile {
public static void main(String[] args) {
String path="D:\test";
File file = new File(path);
File[] files = file.listFiles();
for (File f:files)
{if (f.isFile() && f.exists)
{ f.delete();
system.out.println("successfully deleted");
}else{
system.out.println("cant delete a file due to open or error");
} } }}
rm -rf比FileUtils.cleanDirectory的性能要好得多。
不是一行程序解决方案,但经过大量的基准测试后,我们发现使用rm -rf比使用FileUtils.cleanDirectory快几倍。
当然,如果您有一个小的或简单的目录,这没有关系,但在我们的例子中,我们有多个gb和深嵌套的子目录,使用FileUtils将花费10分钟以上的时间。使用rm -rf只需要1分钟。
下面是我们粗略的Java实现:
// Delete directory given and all subdirectories and files (i.e. recursively).
//
static public boolean clearDirectory( File file ) throws IOException, InterruptedException {
if ( file.exists() ) {
String deleteCommand = "rm -rf " + file.getAbsolutePath();
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec( deleteCommand );
process.waitFor();
file.mkdirs(); // Since we only want to clear the directory and not delete it, we need to re-create the directory.
return true;
}
return false;
}
如果您正在处理大型或复杂的目录,值得一试。