1

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.

2
  • Yes you can ! Use Apache POI API, For further information check this link viralpatel.net/blogs/java-read-write-excel-file-apache-poi Commented Oct 6, 2015 at 9:42
  • 1
    As others suggested it is better to use a third-party library. Parsing csv is non-trivial if the contents contain the delimiter. Commented Oct 6, 2015 at 15:09

2 Answers 2

1

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

}

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.