【问题标题】:How to select few columns from one csv and write it into another csv using java如何从一个csv中选择几列并使用java将其写入另一个csv
【发布时间】:2017-02-20 05:59:07
【问题描述】:

我正在编写一个程序来从一个 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();
            }
        }
    }

}

}

【问题讨论】:

    标签: java


    【解决方案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 而不是自己编写代码。

    【讨论】:

    • 感谢您的回复。但是它在 output.close() 的 finally 块中抛出错误;因为输出是一个未解决的变量。我将其注释掉并运行程序,它没有在我的输出 csv 中填充任何内容。
    • @Aravinda 我刚刚更新了代码并将输出移到了 try 块之外。
    猜你喜欢
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多