如何使用Java

时间:2019-03-21 13:14:35

标签: java performance csv

csv文件1:

a|b|c
a|a|a
b|b|b

csv文件2:

a|b|c
c|c|c
d|d|d

输出csv文件:

a|b|c
a|a|a
b|b|b
c|c|c
d|d|d

这是我尝试合并的代码,但标头重复两次: 当将两个文件合并为一个单独的csv文件时,iam也面临着相同的问题,因为每次我打算做些什么来忽略它时,标题栏都会重复出现。 这是我的下面的代码

  public static void main(String[] args) throws IOException  
{ 
    // PrintWriter object for file3.txt 
    PrintWriter pw = new PrintWriter("file3.txt"); 

    // BufferedReader object for file1.txt 
    BufferedReader br1 = new BufferedReader(new FileReader("file1.txt")); 
    BufferedReader br2 = new BufferedReader(new FileReader("file2.txt")); 


    String line1 = br1.readLine(); 
    String line2 = br2.readLine(); 

    // loop to copy lines of  
    // file1.txt and file2.txt  
    // to  file3.txt alternatively 
    while (line1 != null || line2 !=null) 
    { 
        if(line1 != null) 
        { 
            pw.println(line1); 
            line1 = br1.readLine(); 
        } 

        if(line2 != null) 
        { 
            pw.println(line2); 
            line2 = br2.readLine(); 
        } 
    } 

    pw.flush(); 

    // closing resources 
    br1.close(); 
    br2.close(); 
    pw.close(); 

如何跳过输出文件中的标题列

1 个答案:

答案 0 :(得分:0)

只需跳过第二个和后续CSV文件的第一行:

    for (int i = 0; i < fileNames.length; i++) { 
        System.out.println("Reading from " + fileNames[i]); 

        File f = new File(dir, fileNames[i]);

        BufferedReader br = new BufferedReader(new FileReader(f));

        String line = br.readLine();
        if (i > 0) 
              line = br.readLine(); //just skip the first line

        while (line != null) {
            pw.println(line); 
            line = br.readLine(); 
        } 

        pw.flush(); 
    }