Reputation: 47
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.
Upvotes: 1
Views: 2158
Reputation: 12648
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]);
}
Upvotes: 1
Reputation: 4361
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.
Upvotes: 0