2017-02-18 46 views
0

我正在編寫一個程序以從一個csv中選擇幾列並將其寫入另一個csv。 我能夠選擇我想寫的列,但我無法將它寫入另一個csv。如何從一個csv中選擇幾列並將其寫入另一個csv中使用java

公共類ReadingCSV {

public static void main(String[] args) { 

    String csvFile = "/Users/Desktop/NEW Automation/combined.csv"; 
    String out = "/Users/Desktop/NEW Automation/a.csv"; 
    BufferedReader br = null; 
    String line = ""; 
    String cvsSplitBy = ","; 

    try { 

     br = new BufferedReader(new FileReader(csvFile)); 
     while ((line = br.readLine()) != null) { 

      // use comma as separator 
      String[] mydata = line.split(cvsSplitBy); 
      //System.out.println("[Client = " + mydata[1] + " , Acct_id=" + mydata[2] + "]"); 
      PrintWriter output = new PrintWriter("out", "UTF-8"); 

      output.println(mydata[0] + cvsSplitBy + mydata[1] + cvsSplitBy + mydata[2]); 
     } 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     if (br != null) { 
      try { 
       br.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

} 

}

回答

1

您必須初始化爲PrintWriter您while外塊,你需要關閉它在最後。

public static void main(String[] args) { 

String csvFile = "/Users/Desktop/NEW Automation/combined.csv"; 
String out = "/Users/Desktop/NEW Automation/a.csv"; 
BufferedReader br = null; 
String line = ""; 
String cvsSplitBy = ","; 
PrintWriter output = new PrintWriter("out", "UTF-8"); 
try { 


    br = new BufferedReader(new FileReader(csvFile)); 
    while ((line = br.readLine()) != null) { 

     // use comma as separator 
     String[] mydata = line.split(cvsSplitBy); 
     //System.out.println("[Client = " + mydata[1] + " , Acct_id=" + mydata[2] + "]"); 

     output.println(mydata[0] + cvsSplitBy + mydata[1] + cvsSplitBy + mydata[2]); 
    } 

} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} finally { 
    if (br != null) { 
     try { 
      br.close(); 
      output.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

我還會建議使用開源項目http://opencsv.sourceforge.net/爲csv,而不是解析編寫自己的代碼。

+0

感謝您的回覆。 但是它的throwing錯誤在finally中爲output.close();因爲輸出是一個未解決的變量。 我評論了它並運行該程序,它沒有在我的輸出csv中填充任何東西。 – Aravinda

+0

@Aravinda我剛剛更新了代碼並將try塊的輸出移出。 – Maverick

相關問題