简体   繁体   中英

Extracting only certain columns from one CSV file to write into another CSV file

I am writing from one CSV.1 file to another CSV.2 file. But I only wish to extract certain columns and not everything from CSV.1 file to CSV.2 file. Is there any way to do this? By the way, I am using Java to do this. Thanks.

I would suggest to use some library like OpenCSV . Pleasae have a look at the documentation for this.

But if you want to use your "own code", you could use something like this:

// 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]);

}

You can do it in Java since when you read a CSV file in Java, you read line by line. So for each line you split your line with your CSV separator. You'll have for this line an array of content column by column. Then you skip the column you don't want. You repeat it for each line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM