java - 仅从一个 CSV 文件中提取某些列以写入另一个 CSV 文件

标签 java csv

我正在从一个 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/

相关文章:

java xml上传问题!

python - 对 csv 文件中的每一列进行排序

java - Jersey : location header URI not created correctly

c++ - unsafe.cpp 如何链接到 openJDK 构建系统中的 Unsafe.java

python - 使用python计算csv特定列中的行条目数

python - 按列索引重命名 csv 中的列

python - 如何使用 pandas 从本地网络读取 csv 文件

python - 使用 Python 加速(批量)插入 MySQL

java - Gradle:无法获取类型 'EclipseProject' 的模型

java - 在 Dropwizard 中设置 SSL