我正在从一个 CSV.1 文件写入另一个 CSV.2 文件。但我只想提取某些列,而不是从 CSV.1 文件到 CSV.2 文件的所有内容。有什么办法可以做到这一点吗?顺便说一句,我正在使用 Java 来做到这一点。谢谢。
最佳答案
我建议使用像 OpenCSV 这样的库。请查看相关文档。
但是如果你想使用你的“自己的代码”,你可以使用这样的东西:
// Set your splitter, mostly "," or ";"
String csvSplitter = ";"
// A buffered reader on the input file
BufferedReader br = new BufferedReader(new FileReader("CSV.1"));
// A writer to the output file
PrintWriter output = new PrintWriter("CSV.2", "UTF-8");
// Read line after line until EOF
while ((line = br.readLine()) != null) {
// Split the current line into columns
String[] cols = line.split(csvSplitter);
// Only write the needed columns to the output file (eg. columns at index 4, 5 and 8)
output.println(cols[4] + csvSplitter + cols[5] + csvSplitter + cols[8]);
}
关于java - 仅从一个 CSV 文件中提取某些列以写入另一个 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32966568/