Delete Files with same Prefix String using Java

前端 未结 11 1741
梦谈多话
梦谈多话 2020-12-16 09:11

I have around 500 text files inside a directory with a same prefix in their filename say dailyReport_.

The latter part of the file is the date of the fi

11条回答
  •  误落风尘
    2020-12-16 10:02

    With Java 8:

    public static boolean deleteFilesForPathByPrefix(final String path, final String prefix) {
        boolean success = true;
        try (DirectoryStream 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;
    }
    

    Simple version:

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

    Modify the Path/String argument as needed. You can even convert between File and Path. Path is preferred for Java >= 8.

提交回复
热议问题