使用Java删除具有相同前缀字符串的文件

San*_*non 31 java filenames java-io

我在目录中有大约500个文本文件,文件名中的前缀相同dailyReport_.

文件的后半部分是文件的日期.(例如dailyReport_08262011.txt,dailyReport_08232011.txt)

我想使用Java程序删除这些文件(我可以使用shell脚本并在crontab中添加一个作业,但该应用程序应该由外行使用).

我可以使用这样的东西删除一个文件

        try{
          File f=new File("dailyReport_08232011.txt");
          f.delete();
        }
        catch(Exception e){ 
                System.out.println(e);
        }
Run Code Online (Sandbox Code Playgroud)

但是我可以删除具有特定前缀的文件(例如:dailyReport08对于第8个月)我可以通过使用在shell脚本中轻松地执行此操作rm -rf dailyReport08*.txt.

但是File f=new File("dailyReport_08*.txt");在Java中不起作用(如预期的那样).

现在有没有这样的东西可以在Java中运行而不运行在目录中搜索文件的循环

我可以使用类似于*shell脚本中使用的一些特殊字符来实现这一点吗?

Beg*_*moT 41

不,你不能.Java是一种相当低级的语言 - 与shell脚本相比 - 所以这样的事情必须更加明确地完成.您应该使用folder.listFiles(FilenameFilter)搜索具有所需掩码的文件,并迭代返回的数组,删除每个条目.像这样:

final File folder = ...
final File[] files = folder.listFiles( new FilenameFilter() {
    @Override
    public boolean accept( final File dir,
                           final String name ) {
        return name.matches( "dailyReport_08.*\\.txt" );
    }
} );
for ( final File file : files ) {
    if ( !file.delete() ) {
        System.err.println( "Can't remove " + file.getAbsolutePath() );
    }
}
Run Code Online (Sandbox Code Playgroud)


Pet*_*rey 30

你可以使用循环

for (File f : directory.listFiles()) {
    if (f.getName().startsWith("dailyReport_")) {
        f.delete();
    }
}
Run Code Online (Sandbox Code Playgroud)


Nir*_*ane 10

爪哇 8:

final File downloadDirectory = new File("directoryPath");   
    final File[] files = downloadDirectory.listFiles( (dir,name) -> name.matches("dailyReport_.*?" ));
    Arrays.asList(files).stream().forEach(File::delete)
Run Code Online (Sandbox Code Playgroud)


tb-*_*tb- 8

使用Java 8:

public static boolean deleteFilesForPathByPrefix(final String path, final String prefix) {
    boolean success = true;
    try (DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(Paths.get(path), prefix + "*")) {
        for (final Path newDirectoryStreamItem : newDirectoryStream) {
            Files.delete(newDirectoryStreamItem);
        }
    } catch (final Exception e) {
        success = false;
        e.printStackTrace();
    }
    return success;
}
Run Code Online (Sandbox Code Playgroud)

简单版本:

public static void deleteFilesForPathByPrefix(final Path path, final String prefix) {
    try (DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(path, prefix + "*")) {
        for (final Path newDirectoryStreamItem : newDirectoryStream) {
            Files.delete(newDirectoryStreamItem);
        }
    } catch (final Exception e) { // empty
    }
}
Run Code Online (Sandbox Code Playgroud)

根据需要修改Path/String参数.您甚至可以在文件和路径之间进行转换.Java> = 8时首选路径.


Luc*_*s T 6

我知道我参加聚会迟到了。但是,为了将来的参考,我想贡献一个不涉及循环的 java 8 流解决方案。

它可能不漂亮。我欢迎提出建议,使其看起来更好。然而,它的作用是:

Files.list(deleteDirectory).filter(p -> p.toString().contains("dailyReport_08")).forEach((p) -> {
    try {
        Files.deleteIfExists(p);
    } catch (Exception e) {
        e.printStackTrace();
    }
});
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用Files.walk它将深度优先遍历目录。也就是说,如果文件被埋在不同的目录中。


Eri*_*rik 5

FileFilter像这样使用:

File dir = new File(<path to dir>);
File[] toBeDeleted = dir.listFiles(new FileFilter() {
  boolean accept(File pathname) {
     return (pathname.getName().startsWith("dailyReport_08") && pathname.getName().endsWith(".txt"));
  } 

for (File f : toBeDeleted) {
   f.delete();
}
Run Code Online (Sandbox Code Playgroud)