如何使用 Java 将文本附加到一个目录中的多个文件

How to append text to multiple files in one directory using Java

我有很多包含一些数据的 .txt 文件

1.txt
2.txt
3.txt
...

我想将相同的文本添加到同一目录中的每个 txt 文件,例如 "hello world"

我知道在那种情况下如何处理一个文件,但如何处理多个文件?我必须使用 Java...

来做到这一点

我认为您想做的是列出目录中的所有文件,然后处理每个文件。如果是这样你可以做

File[] children = dir.listFiles();
for (File child: children) {
    if (child.isFile()) {
        // append text
    }
}

我已经省略了附加数据的代码,因为您说您已经知道该怎么做。在这一点上,它只是将该代码应用于每个文件的情况

您可以创建一个包含目录的文件:

File directory = new File("pathOfYourDirectory");

然后就可以得到所有的从属文件和目录了:

File[] subDirectories = directory.listFiles();

现在你可以遍历这个数组了。但是你应该检查每个文件是否是一个文件。然后您可以获取此文件并附加文本。

for (File subDir: subDirectories ) {
    if (subDir.isFile()) {
        // do your stuff
    }
}

您可以使用 java.nio 和 Java 8 项功能来列出文件并为每个文件执行一些操作。有一种方法可以将文本附加到文件。

看到这个例子并阅读代码中的一些注释,请:

public static void main(String[] args) {
    // define the directory that contains the text files
    String dir = "U:\workspace\git\ZZ--Temp\TextFiles";
    Path dirPath = Paths.get(dir);
    // predefine some lines to be appended to every file
    List<String> linesToBeAppended = new ArrayList<>();
    linesToBeAppended.add("Hello new line in the file!");

    try {
        // go through all files in the directory (tested with .txt files only)
        Files.list(dirPath)
            // filter only files
            .filter(Files::isRegularFile)
            .forEach(filePath -> {
                try {
                    // append the predefined text to the file
                    Files.write(filePath, linesToBeAppended, StandardOpenOption.APPEND);
                } catch (IOException e) {
                    System.err.println("Could not append text to file " 
                            + filePath.toAbsolutePath().toString());
                    e.printStackTrace();
                }
            });
    } catch (IOException e) {
        System.err.println("Could not list files in " 
                + dirPath.toAbsolutePath().toString());
        e.printStackTrace();
    }
}

不幸的是,由于 Java 8 功能 forEach 的不同范围,嵌套 try-catch 是必需的。它很难看,但优点是您可以通过列出文件或访问文件来区分抛出的 Exception

编辑
如果要向文件添加新的第一行,则必须读取并重写文件。请参阅此示例,它与第一个示例略有不同:

public static void main(String[] args) {
    // define the directory that contains the text files
    String dir = "U:\workspace\git\ZZ--Temp\TextFiles";
    Path dirPath = Paths.get(dir);

    try {
        // go through all files in the directory (tested with .txt files only)
        Files.list(dirPath)
            // filter only files
            .filter(Files::isRegularFile)
            .forEach(filePath -> {
                // predefine some lines to be appended to every file
                List<String> linesToBeAppended = new ArrayList<>();
                // add the first line as predefined first line
                linesToBeAppended.add("Hello another line in the file!");

                try {
                    // then read the file and add its lines to the list with
                    // that already contains the new first line
                    linesToBeAppended.addAll(Files.readAllLines(filePath));
                    // append the extended text to the file (again),
                    // but this time overwrite the content
                    Files.write(filePath, linesToBeAppended,
                                StandardOpenOption.TRUNCATE_EXISTING);
                } catch (IOException e) {
                    System.err.println("Could not append text to file " 
                            + filePath.toAbsolutePath().toString());
                    e.printStackTrace();
                }
            });
    } catch (IOException e) {
        System.err.println("Could not list files in " 
                + dirPath.toAbsolutePath().toString());
        e.printStackTrace();
    }
}

Another important difference is the flag in Files.write, which is not APPEND anymore, but TRUNCATE_EXISTING because you read the file into a list of String representing the lines, then you add that collection to the one that already contains the new first line. Afterwards, you just write the lines again including the new first line.