I'm trying to create a program that writes all the data from excel to multiple csv files.
Currently, my program creates n number of files, and only the last row of excel is being written on the last csv file.
Programming Background Observation:
It seems like the file is writing. But for each written row, it somehow creates the same file 250 times. It erases the row that was written last.
I may have some problems using the OutputStream or BufferedWriter. I just can't figure out what it is.
writeRow() method:
public static void writeRow(BufferedWriter bw, Cell[] row) throws IOException {
if (row.length > 0) {
bw.write(row[0].getContents());
for (int j = 1; j < row.length; j++) {
bw.write(',');
bw.write(row[j].getContents());
}
}
}
setFile() method:
public static BufferedWriter setFile (int i) throws IOException {
i=i/250;
File f = new File(dir + "file-" + (i+1) + ".csv");
// If i has changed, create a new file. Else, append to current file.
String encoding = "UTF8";
OutputStream os = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
Boolean append = null;
try {
// If i has changed, create a new file, else append.
if (i%250==0) {
append = new Boolean("TRUE");
os = new FileOutputStream(f,append);
} else {
append = new Boolean("FALSE");
os = new FileOutputStream(f, append);
}
osw = new OutputStreamWriter(os, encoding);
bw = new BufferedWriter(osw);
} finally {
os.close();
osw.close();
}
return bw;
}
Here are the exceptions.
Exception in thread "main" java.io.IOException: Stream closed
at sun.nio.cs.StreamEncoder.ensureOpen(Unknown Source)
at sun.nio.cs.StreamEncoder.write(Unknown Source)
at java.io.OutputStreamWriter.write(Unknown Source)
at java.io.BufferedWriter.flushBuffer(Unknown Source)
at java.io.BufferedWriter.flush(Unknown Source)
at Main.main(Main.java:46)
Below are some of the links to the code.
What am I doing wrong?
Here is the svn trunk:
https://franz-opensource.googlecode.com/svn/trunk/ExcelToCsv -
- Click here for the Java Main code like the one above.
- Click here to download the sample excel file
- Click here for the jexcelapi download