簡體   English   中英

使用Java.IO合並文件夾中的所有.txt文件

[英]Merging all .txt files in a folder using Java.IO

我試圖將所有.txt文件合並到一個特定的文件夾中,並創建一個output.txt文件。 我是Java學習Java.IO包的Java.IO 這是我的程序編譯好並創建一個輸出文件,但不寫任何東西。 我驗證了我的輸入文本文件,它有數據。

import java.io.*;

class  Filemerger
{
    public static void main(String[] args) throws IOException
    {
        PrintWriter pw = new PrintWriter("true1.txt");      
        File f = new File("E:\\A");
        String[] s = f.list();
        for (String s1 : s)
        {
            File f1 = new File(f, s1);
            BufferedReader br = new BufferedReader(new FileReader(f1));
            String line = br.readLine();
            while (line != null)
            {
                pw.println(line);
                line = br.readLine();
            }
        }
        pw.flush();
        pw.close();
    }
}

我認為你的錯誤是最小的,也許有些路徑是錯誤的或類似的東西。 無論如何,您應該使用名為NIO的新IO API來與文件進行交互。 關鍵類是位於java.nio包中的PathsFiles

class  Filemerger
{
    public static void main(String[] args) throws IOException
    {
        Path output = Paths.get("true1.txt");
        Path directory = Paths.get("E:\\A");
        Stream<Path> filesToProcess = Files.list(directory);

        // Iterate all files
        filesToProcess.forEach(path -> {
            // Get all lines of that file
            Stream<String> lines = Files.lines(path);
            // Iterate all lines
            lines.forEach(line -> {
                // Append the line separator
                String lineToWrite = line + System.lineSeparator();

                // Write every line to the output file
                Files.write(output, lineToWrite.getBytes(StandardCharsets.UTF_8));
            });
        });
    }
}

或者,如果您只想從所有文件中收集所有行而不映射到它們所屬的文件,您也可以使用Stream#flatMap方法:

Path output = Paths.get("true1.txt");
Path directory = Paths.get("E:\\A");

Files.list(directory)
    .flatMap(Files::lines)
    .forEach(line -> {
        Files.write(output, (line + System.lineSeparator())
            .getBytes(StandardCharsets.UTF_8));
    });

請注意, Files#write和其他方法也接受一組您可以設置的選項。 例如,如果文件尚不存在則應該創建。 或者,如果它已經存在,則應該追加內容還是應刪除舊內容。

因此,請查看文檔頁面:

你的代碼沒有寫任何文件。 也許就是println()方法。 請根據您的要求調整輸入和輸出文件的路徑。

略有修改:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

public class MergeTextFiles {
    public static void main(String[] args) throws IOException {
        File f = new File("./src/main/resources");

        File merged = new File("./src/main/resources/merged.txt");
        if (!merged.exists()) {
            merged.createNewFile();
        }

        PrintWriter pw = new PrintWriter(merged);

        String[] s = f.list();
        System.out.println("list of files-> " + Arrays.asList(s));

        for (String s1 : s) {
            File f1 = new File(f, s1);
            BufferedReader br = new BufferedReader(new FileReader(f1));

            String line = "";
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                pw.println(line);
            }
        }
        pw.flush();
        pw.close();
    }
}

更新:它不是'println'。

您應該始終在main方法中處理異常,否則將忽略異常。

如果目錄不存在,f.list()返回null(!);

如果目錄包含子目錄,則還將返回這些子目錄的名稱,因此您必須測試文件確實是文件;

當您打開文件時,您應該關閉它或(更好)使用帶有資源的try塊:

public static void main(String[] args)
{
    try(PrintWriter pw = new PrintWriter("true1.txt")) {
        File f = new File("E:\\A");
        String[] s = f.list();
        if (s == null) {
            throw new IOException("Directory doesn't exist: " + f);
        }
        for (String s1 : s)
        {
            File f1 = new File(f, s1);
            if (!f1.isFile()) {
                continue;
            }
            try (Reader reader = new FileReader(f1);
                    BufferedReader br = new BufferedReader(reader)) {
                String line = br.readLine();
                while (line != null)
                {
                    pw.println(line);
                    line = br.readLine();
                }
            }
        }
    } catch (Throwable e) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM