简体   繁体   English

Java删除文件/目录,等同于linux“ rm -rf / tmp / garbagedir *”

[英]Java delete file/directory equivalent of linux “rm -rf /tmp/garbagedir*”

Given a bunch of tmp directories and tmp files like this: 给定一堆tmp目录和tmp文件,如下所示:

/tmp/garbagedir1/
/tmp/garbagedir2/
/tmp/garbagedir3/
/tmp/deleteme.txt
/tmp/deleteme.log

In Linux, we can execute one simple shell command to recursively force delete all of these: 在Linux中,我们可以执行一个简单的shell命令来递归地强制删除所有这些命令:

$ rm -rf /tmp/garbagedir* /tmp/deleteme*

All of the above files and directories are deleted, including all the files that may be in the directories. 以上所有文件和目录均被删除,包括目录中可能存在的所有文件。 All other files in the /tmp directory are not touched. / tmp目录中的所有其他文件均未触及。

There are many ways to do this in Java, but what is the simplest way that does not involve lots of Java style boilerplate code and still be platform independent? 在Java中有很多方法可以做到这一点,但是最简单的方法又不涉及很多Java样式样板代码,却仍然是平台无关的?

you may use the FileUtils class of Apache Commons IO; 您可以使用Apache Commons IO的FileUtils类; with it you can do something like that: 使用它,您可以执行以下操作:

FileUtils.forceDelete(new File("/home/test"));

Links to the documentation: http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html 指向文档的链接: http : //commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html

Hope it helps 希望能帮助到你

Angelo 安杰洛

Note, I haven't tested this code so don't try it first on anything important! 请注意,我尚未测试此代码,因此请不要在任何重要的东西上先尝试!

You can use the Java NIO2 SimpleFileVisitor to recursviely walk thru directories and their children. 您可以使用Java NIO2 SimpleFileVisitor递归地遍历目录及其子目录。 First we create a new FileVisitor that will delete all files that it sees and then delete the empty directories once all its children have been deleted. 首先,我们创建一个新的FileVisitor,它将删除它看到的所有文件,然后在删除所有子目录后删除空目录。

  FileVisitor recursiveDeleteVisitor = new SimpleFileVisitor<Path>() {

  @Override
  public FileVisitResult visitFile(Path file,
          BasicFileAttributes attrs) throws IOException {

      System.out.println("Deleting file: " + file);
      Files.delete(file);
      return CONTINUE;
  }

  @Override
  public FileVisitResult postVisitDirectory(Path dir,
          IOException exc) throws IOException {

      System.out.println("Deleting dir: " + dir);
      if (exc == null) {
          Files.delete(dir);
          return CONTINUE;
      } else {
          throw exc;
      }
  }

 };

This might count as boiler plate, but you would only have to write the FileVisitor instance once and then you can re-use it as part of a utility class. 这可能算作样板,但是您只需要编写一次FileVisitor实例,然后就可以将其作为实用程序类的一部分重新使用。 I'm not sure why something like this isn't included in the JDK. 我不确定为什么JDK中不包含这样的内容。

Anyway, once you have that, then iterate over the children of /tmp and recursively delete any directories that match: 无论如何,一旦有了它,然后遍历/tmp并递归删除任何匹配的目录:

 File root = new File("/tmp");
 for(File child : root.listFiles()){
      //optionally use Pattern class for regex
      if(child.getName().startsWith("garbagedir")){
          Files.walkFileTree(child.toPath(), recursiveDeleteVisitor);
      }
 }

EDIT 编辑


User fge pointed out that Java 7 has a Files.newDirectoryStream() method that will return a DirectoryStream object that can be used to iterate over the children instead of using the old File.listFiles() which returns an array which means all the objects are created in memory before iteration. 用户fge指出Java 7有一个Files.newDirectoryStream()方法,该方法将返回一个DirectoryStream对象,该对象可用于遍历子对象,而不是使用旧的File.listFiles()返回一个数组,这意味着所有对象都是在迭代之前在内存中创建。 This could save you from memory problems if you have lots of files. 如果您有很多文件,这可以使您免于内存问题。 You can even use the globbing pattern as a 2nd String argument. 您甚至可以将通配符模式用作第二个String参数。

Path root = Paths.get("/tmp");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(root, "garbagedir*")) {
   for (Path entry: stream) {
       Files.walkFileTree(child.toPath(), recursiveDeleteVisitor);
    }
 }

The new file API has all the tools you need: 新的文件API具有您需要的所有工具:

Feel free to salvage the recursive deletion example, and note that it can be improved. 请随意挽救递归删除示例,并注意可以进行改进。 In particular, this one will stop at the first deletion error, but it is trivial to modify so that it continues in this case instead. 特别是,此操作将在第一个删除错误时停止,但是修改很简单,因此在这种情况下可以继续操作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用file.delete()删除远程文件更好,或者使用rm -rf进行ProcessBuilder调用更好? - Deleting remote files is better with file.delete() or making ProcessBuilder call with rm -rf? Java程序无法执行它写入/ tmp的文件,没有此类文件或目录 - Java program can't execute file it writes to /tmp, no such file or directory java:如何将 jar 文件中的目录复制到 tmp 目录? - java: How to copy a directory in a jar file to a tmp dir? 删除文件并将其移动到Java中的目录 - Delete and move file to a directory in java 如何使用Java从目录中删除文件? - How to delete a file from a directory using Java? 如何在fileupload struts2中删除.tmp文件 - How to delete .tmp file in fileupload struts2 UnsatisfiedLinkError:/tmp/snappy-1.1.4-libsnappyjava.so 加载共享库 ld-linux-x86-64.so.2 时出错:没有这样的文件或目录 - UnsatisfiedLinkError: /tmp/snappy-1.1.4-libsnappyjava.so Error loading shared library ld-linux-x86-64.so.2: No such file or directory 使用rm -rf /Library/Java/JavaVirtualMachines/jdkmajor.minor.macro[_update].jdk在Mac上卸载jdk 7后出现问题 - I have problems after uninstalling jdk 7 on mac with rm -rf /Library/Java/JavaVirtualMachines/jdkmajor.minor.macro[_update].jdk 如何以编程方式删除linux中某个目录中存在的文件 - How to delete a file present in some directory in linux programmatically 具有Java的MAC OSX和Linux中目录中的文件和目录列表 - List of file and directory in directory in MAC OSX and Linux with Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM