gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:52:17 25 4
gpt4 key购买 nike

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

}

}

最佳答案

您必须在 while block 之外初始化 Printwriter,并且需要在 finally 中关闭它。

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

关于java - 如何使用java从一个csv中选择几列并将其写入另一个csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42312329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com