使用其他CSV文件的输入

时间:2016-07-28 12:25:23

标签: java csv

我有两个CSV文件input1.txtinput2.txt。我需要从input1.txt中取一个值并在input2.txt中搜索它,如果找到,则将整个记录从input2.txt写入另一个文件。

我已经编写了以下代码并且它正在运行,但速度非常慢。有没有更有效的方法来实现这一目标?

import java.io.*;

public class FileCompare
{
    private static final EOL = System.getProperty("line.separator");

    public static void main(String args[])
        throws IOException
    {
        FileReader in = null;
        FileReader comp = null;
        FileWriter out = null;
        FileWriter out2 = null;

        try {
            in = new FileReader("input1.txt");  //file containing value to search
            out = new FileWriter("matching.txt"); // file to write output
            out2 = new FileWriter("notfound.txt"); // file to write non matching
            BufferedReader br = new BufferedReader(in);      
            String p, q;
            boolean done;

            // Read the input file line by line
            while ((p = br.readLine()) != null) {
                done = false;
                String str = p;
                String delims = "[\\t]"; 
                String[] tokens = str.split(delims);

                Long acno = Long.parseLong(tokens[5]);  // value in input1.txt  to be checked against input2.txt
                Long si = Long.parseLong(tokens[31]);

                comp = new FileReader ("input2.txt");  // file containing  bulk data  
                BufferedReader bbr = new BufferedReader (comp); // opening bulk file 

                while (!done) {  // flag to break the second file operation if matching value found
                    while ((q = bbr.readLine()) != null) {  // loop to read bulk file 
                        String delim2 = "[\\t]"; 
                        String[] token2 = q.split(delim2); // splitting file based on delimiter
                        Long acno1 = Long.parseLong(token2[5]);
                        Long si1 = Long.parseLong(token2[31]);

                        if (acno1.equals(acno)) {  // checking the condition 
                            out.write(q + EOL); // writing the matching entry(entire row) from input2.txt
                            done = true;  // changing the flag value , so that control will go to input file for next line
                            break;  // breaking the bulk reading loop , because we got the value as per condition
                        } else {  // if condition not satisfies 
                            out2.write(p + EOL);  //writing entry input1.txt if it is not matching
                            done = true;  //  flag value changing , so that control will go to input file for next
                        }
                    }
                }
            }
        } finally {
            if (in != null) in.close();
            if (out != null) out.close();
            if (out2 != null) out2.close();
        }
    }
}

0 个答案:

没有答案