如何从一个csv中选择几列,并使用java将其写入另一个csv

时间:2017-02-18 07:18:11

标签: java

我正在编写一个程序,从一个csv中选择几个列并将其写入另一个csv。 我能够选择我想写的列,但我无法将其写入另一个csv。

公共课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 个答案:

答案 0 :(得分:1)

您必须在while块之外初始化Printwriter,并且最后需要将其关闭。

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,而不是编写自己的代码。