
June 9th, 2011, 07:40 PM
|
|
Registered User
|
|
Join Date: Jun 2011
Posts: 2
Time spent in forums: 6 h 31 m 37 sec
Reputation Power: 0
|
|
|
Java CSV reader/writer advice?
I am currently working on a simple .csv reader/writer class for an app that I am building and would like some advice or input. The current code seems to work well but I am fairly new to using external files with my programs so I'd like to hear if there is any newer or more efficient way to do this than what I have posted or if there are any major flaws that I have missed.
Thanks.
Code:
import java.io.*;
import java.util.ArrayList;
public class CSVData {
public ArrayList<String[]> readCSV(String filename) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader(filename));
ArrayList<String[]> rows = new ArrayList<String[]>();
String line = reader.readLine();
while(line != null) {
String[] row = line.split(",");
for (int x = 0; x<row.length; x++) {
row[x] = row[x].trim();
}
rows.add(row);
line = reader.readLine();
}
return rows;
}
public void writeCSV(ArrayList<String[]> data, String filename) throws Exception {
FileWriter writer = new FileWriter(filename);
for (int x = 0; x < data.size(); x++) {
String[] line = data.get(x);
for (int y = 0; y < line.length; y++) {
if (y < line.length-1) {
writer.append(line[y]+",\t");
} else {
writer.append(line[y]);
}
}
writer.append("\n");
}
writer.flush();
writer.close();
}
}
|