使用java逐行合并两个文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19049785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:41:00  来源:igfitidea点击:

Merge Two text files line by line using java

javamergedataoutputstream

提问by Avisek Panda

First text file A.txt;

第一个文本文件 A.txt

asdfghjklqw12345 qwe3456789
asdfghjklqw12345 qwe3456789

asdfghjklqw12345 qwe3456789
asdfghjklqw12345 qwe3456789

Second text file B.txt;

第二个文本文件 B.txt

|Record 1: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month| |Record 2: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|

|记录 1:拒绝 - 表 AUTHORIZATION_TBL,列 AUTH_DATE.ORA-01843 上的错误:无效月份| |记录 2:拒绝 - 表 AUTHORIZATION_TBL,列 AUTH_DATE.ORA-01843 上的错误:无效月份|

Third text file C.txt;

第三个文本文件 C.txt

asdfghjklqw12345 qwe3456789 |Record 1: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|

asdfghjklqw12345 qwe3456789 |记录 1:拒绝 - 表 AUTHORIZATION_TBL 上的错误,列 AUTH_DATE.ORA-01843:无效月份|

asdfghjklqw12345 qwe3456789 |Record 2: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|

asdfghjklqw12345 qwe3456789 |记录 2:拒绝 - 表 AUTHORIZATION_TBL 上的错误,列 AUTH_DATE.ORA-01843:无效月份|

for the above situation where I want to merge two lines from two different text files into one line.My code is below

对于上述情况,我想将来自两个不同文本文件的两行合并为一行。我的代码如下

    List<FileInputStream> inputs = new ArrayList<FileInputStream>();
    File file1 = new File("C:/Users/dell/Desktop/Test/input1.txt");
    File file2 = new File("C:/Users/dell/Desktop/Test/Test.txt");

    FileInputStream fis1;
    FileInputStream fis2;

    try {
        fis1 = new FileInputStream(file1);
        fis2= new FileInputStream(file2);

        inputs.add(fis1);
        inputs.add(fis2);

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    int total = (int) (file1.length() + file2.length());
    System.out.println("total length is " + total);

    SequenceInputStream sis = new                                                            SequenceInputStream(Collections.enumeration(inputs));
    try {
        System.out.println("SequenceInputStream.available() = "+ sis.available());

        byte[] merge = new byte[total];

        int soFar = 0;
        do {
            soFar += sis.read(merge,total - soFar, soFar);
        } while (soFar != total);
        DataOutputStream dos = new DataOutputStream(new        FileOutputStream("C:/Users/dell/Desktop/Test/C.txt"));
        soFar = 0;
        dos.write(merge, 0, merge.length);
        dos.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

回答by Kayz

You might want to have a look at BufferedReaderand BufferedWriter. Show us what you tried and where you are stuck and we are happy to provide more help.

您可能想看看 BufferedReaderBufferedWriter。向我们展示您尝试过的内容以及您遇到的问题,我们很乐意提供更多帮助。

回答by Masudul

Here is code:

这是代码:

public class MergeText {
    public static void main(String[] args) throws IOException{
        String output="";
        try(Scanner sc1=new Scanner((new File("A.txt")));
        Scanner sc2=new Scanner((new File("B.txt")))){

        while(sc1.hasNext() || sc2.hasNext()){
            output+=sc1.next() +" "+ sc2.next();
            output+="\n";
        }

        }

        try(PrintWriter pw=new PrintWriter(new File("C.txt"))){
        pw.write(output);
        }        
    }
}

回答by wahidd

Merging all txt file from a folder can be done in the following way:

可以通过以下方式合并文件夹中的所有 txt 文件:

public static void main(String[] args) throws IOException {
        ArrayList<String> list = new ArrayList<String>();

        //Reading data files
        try {

            File folder = new File("path/inputFolder");
            File[] listOfFiles = folder.listFiles();

            for (int i = 0; i < listOfFiles.length; i++) {
                File file = listOfFiles[i];
                if (file.isFile() && file.getName().endsWith(".txt")) {
                    BufferedReader t = new BufferedReader (new FileReader (file));
                    String s = null;
                    while ((s = t.readLine()) != null) {                         
                        list.add(s);        
                    }
                    t.close();
                } 
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        //Writing merged data file
        BufferedWriter writer=null;
        writer = new BufferedWriter(new FileWriter("data.output/merged-output.txt"));
        String listWord;              
        for (int i = 0; i< list.size(); i++)
        {
            listWord = list.get(i);
            writer.write(listWord);
            writer.write("\n");
        }
        System.out.println("complited");
        writer.flush();
        writer.close();    
    }

回答by Mathomatic

Improved on Masudul's answer to avoid compilation errors:

改进了 Masudul 的回答以避免编译错误:

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class MergeText {
    public static void main(String[] args) throws IOException {
        StringBuilder output = new StringBuilder();
        try (Scanner sc1 = new Scanner((new File("C:\Users\YourName\Desktop\A.txt")));
             Scanner sc2 = new Scanner((new File("C:\Users\YourName\Desktop\B.txt")))) {

            while (sc1.hasNext() || sc2.hasNext()) {
                String s1 = (sc1.hasNext() ? sc1.next() : "");
                String s2 = (sc2.hasNext() ? sc2.next() : "");
                output.append(s1).append(" ").append(s2);
                output.append("\n");
            }
        }
        try (PrintWriter pw = new PrintWriter(new File("C:\Users\mathe\Desktop\Fielddata\RESULT.txt"))) {
            pw.write(output.toString());
        }
    }
}