Javaを使用して一つのディレクトリに複数のファイルにテキストを追加する方法

ドイツVaranytsya:

私はいくつかのデータを.txtファイルがたくさんあります

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

私は、例えば、同じテキストを追加したい"hello world"と同じディレクトリからすべてのtxtファイルに。

私はそのような場合には、一つのファイルで作業する方法を知っているが、どのように複数のファイルを扱うには?私はJavaを使用してそれを行う必要があり...

deHaar:

あなたは使用することができます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();
    }
}

残念ながら、ネストされたがtry- catchのJava 8の特徴の異なるスコープによるものが必要ですforEachそれは醜いですが、あなたは区別できるという利点があるExceptionファイルをリストまたは1つにアクセスすることにより、いずれかのスロー秒。

EDIT
ファイルに新しい最初の行を追加したい場合は、ファイルを読み込んで再記述する必要があります。最初の1からわずかに異なっている。この例を参照してください:

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();
    }
}

もう一つの重要な違いは、中のフラグでFiles.writeはありませんが、APPENDもはや、しかし、TRUNCATE_EXISTINGあなたはのリストにファイルを読み込むためStringの行を表す、あなたはすでに新しい最初の行が含まれているものにそのコレクションを追加します。その後、あなたはもう一度新しい最初の行を含む行を記述します。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=332018&siteId=1