亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用Java將文本附加到一個目錄中的多個文件

如何使用Java將文本附加到一個目錄中的多個文件

梵蒂岡之花 2023-06-08 19:16:24
我有很多包含一些數據的 .txt 文件1.txt 2.txt 3.txt ...我想添加相同的文本,例如"hello world"添加到同一目錄中的每個 txt 文件。我知道在那種情況下如何處理一個文件,但如何處理多個文件呢?我必須使用 Java 來做到這一點......
查看完整描述

3 回答

?
料青山看我應如是

TA貢獻1772條經驗 獲得超8個贊

您可以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 功能的不同范圍,嵌套try-是必需的。它很丑陋,但優點是您可以通過列出文件或訪問文件來區分拋出的 s 。catchforEachException


編輯

如果要在文件中添加新的第一行,則必須讀取并重寫文件。請參閱此示例,它與第一個示例略有不同:


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表示行的列表中,然后將該集合添加到已經包含新的第一行的集合中。之后,您只需再次編寫這些行,包括新的第一行。


查看完整回答
反對 回復 2023-06-08
?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

我認為您想要做的是列出目錄中的所有文件,然后處理每個文件。如果是這樣的話你可以做


File[] children = dir.listFiles();

for (File child: children) {

    if (child.isFile()) {

        // append text

    }

}

我已經省略了附加數據的代碼,因為您說您已經知道該怎么做。在這一點上,它只是將代碼應用于每個文件的情況


查看完整回答
反對 回復 2023-06-08
?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

您可以創建一個包含目錄的文件:


File directory = new File("pathOfYourDirectory");

然后你可以得到所有的從屬文件和目錄:


File[] subDirectories = directory.listFiles();

現在你可以遍歷這個數組了。但是你應該檢查每個文件是否是一個文件。然后您可以獲取此文件并附加文本。


for (File subDir: subDirectories ) {

    if (subDir.isFile()) {

        // do your stuff

    }

}


查看完整回答
反對 回復 2023-06-08
  • 3 回答
  • 0 關注
  • 170 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號