我正在编写一个Java实用程序,我想将基于列名的特定列从一个CSV而不是 ArrayIndex 传输到另一个CSV文件。
下面是当我根据 array Index 选择特定列但我只想根据 Column Name 过滤列的程序,该程序绝对正常。 / p>
package be.ing.data;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class ImportExportCSV{
public static void main(String[] args){
// Set your splitter, mostly "," or ";"
String csvFile = "C:/Data/input_file.csv";
String exportCSVFile = "C:/Data/output_file.csv";
// String csvSplitter = "\t";
String csvSplitter = ",";
String line = "";
BufferedReader br = null;
PrintWriter output = null;
Date date = new Date();
try {
// A buffered reader on the input file
br = new BufferedReader(new FileReader(csvFile));
// A writer to the output file
output = new PrintWriter(exportCSVFile, "UTF-8");
// Read line after line until EOF
int count = 0;
long startTime = System.nanoTime();
System.out.println("Start Execution Time : "+startTime);
while ((line = br.readLine()) != null) {
String[] cols = line.split(csvSplitter);
output.println(cols[0] + csvSplitter +
cols[20]);
count++;
}
System.out.println("Total Record count :"+count);
long endTime = System.nanoTime();
System.out.println("Completion Time : "+ (endTime-startTime));
System.out.println("Time in seconds"+ TimeUnit.SECONDS.convert(endTime, TimeUnit.NANOSECONDS));
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
答案 0 :(得分:0)
您必须将String[] cols
转换为List<String>
,以便根据列名获取列索引,然后使用该索引来访问csv文件每一行的值:< / p>
例如,如果要为csv文件的每一行打印列"myColumnName"
的值:
String[] cols = line.split(csvSplitter);
List<String> columns = Arrays.asList(cols);
System.out.println(cols[columns.indexOf("myColumnName")]);