FileWriter stops unexpectedly

I am trying to use XLS2CSV to convert an Excel file to a csv text file. I modified the existing class slightly to change PrintStream to Writer so I could write to a file using FileWriter.

Anyway, it writes to the System.out.PrintStream fine, everything shows up. But when I open the file the last few lines are missing. My first assumption was that the application was closing the connection before it could complete the writes but I used an infinite loop to try and test that but even leaving the application open it does the same thing.

Does anyone have any ideas why this will print to PrintStream fine but not write to a file? I changed the FileWriter to CSVWriter and it seemed to write less data so I'm thinking it does have something to do with the connection getting closed but I'm fairly new to input and output so any help would be appreciated.

Here is a functional example (you'll need to modify the file name for the input and output)

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;

public class XLS2CSV {
private InputStream in;
private Writer out;
private DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");

public XLS2CSV(InputStream in, Writer out) {
    if (null == in) {
        throw new IllegalArgumentException("in cannot be null.");
    }
    if (null == out) {
        throw new IllegalArgumentException("out cannot be null.");
    }
    this.in = in;
    this.out = out;
}

public void process() throws IOException {
    process(in);
}

private void process(InputStream in) throws IOException {
    HSSFWorkbook w = new HSSFWorkbook(in);
    int numSheets = w.getNumberOfSheets();
    for (int i = 0; i < numSheets; i++) {
        HSSFSheet sheet = w.getSheetAt(i);
        int lastRow = 0;
        for (Iterator rows = sheet.rowIterator(); rows.hasNext();) {
            Row row = (Row) rows.next();
            int lastCol = 0;
            for (Iterator cells = row.cellIterator(); cells.hasNext();) {
                Cell cell = (Cell) cells.next();
                String cellValue = "";
                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_FORMULA:
                    FormulaEvaluator fe = new HSSFFormulaEvaluator(w);
                    CellValue v = fe.evaluate(cell);
                    switch (v.getCellType()) {
                    case Cell.CELL_TYPE_BOOLEAN:
                        cellValue = String.valueOf(v.getBooleanValue());
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        cellValue = String.valueOf(v.getNumberValue());
                        break;
                    case Cell.CELL_TYPE_STRING:
                        cellValue = String.valueOf(v.getStringValue());
                        break;
                    case Cell.CELL_TYPE_BLANK:
                        break;
                    case Cell.CELL_TYPE_ERROR:
                        break;
                        // CELL_TYPE_FORMULA will never happen
                    case Cell.CELL_TYPE_FORMULA:
                        break;
                    }
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        Date date = cell.getDateCellValue();
                        cellValue = dateFormat.format(date);
                    } else {
                        cellValue = String.valueOf(cell);
                    }
                    break;
                default:
                    cellValue = String.valueOf(cell);
                }
                int cellIndex = cell.getColumnIndex();
                while (lastCol < cellIndex) {
                    System.out.print(",");
                    out.append(",");
                    lastCol++;
                }
                System.out.print(cellValue);
                out.append(cellValue);
            }
            while (lastRow <= row.getRowNum()) {
                System.out.println();
                out.append('\n');
                lastRow++;
            }
        }
    }
}

public void setDateFormat(DateFormat dateFormat) {
    if (null == dateFormat) {
        throw new IllegalArgumentException("dateFormat cannot be null.");
    }
    this.dateFormat = dateFormat;
}

public DateFormat getDateFormat() {
    return dateFormat;
}

public static void process(File file, Writer out) throws IOException {
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(file);
        new XLS2CSV(new BufferedInputStream(fis), out).process();
    } finally {
        if (null != fis) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

public static void main(String[] args) {

    File xlsFile = new File("C:/Documents and Settings/berlgeof/Desktop/Commit Dates 12-10-2013.xls");
    if (!xlsFile.exists()) {
        System.err.println("Not found or not a file: " + xlsFile.getPath());
        return;
    }

    Writer writer = null;
    try {
        writer = new FileWriter("lib/files/converted/Temp Commit Data.csv");
    } catch (IOException e) {
        e.printStackTrace();
    }
    XLS2CSV xls2csv = null;
    try {
        xls2csv = new XLS2CSV(new FileInputStream(xlsFile), writer);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        xls2csv.process();
    } catch (IOException e) {
        e.printStackTrace();
    }

//      while(true) {}  // Let me close the application


}
Jon Skeet
people
quotationmark

You're not closing the writer, which means there's data still in the buffer. You should close it (and all the other streams etc) in finally blocks, or use a try-with-resources statement if you're using Java 7.

Also note that the way you're currently "handling" exceptions is to pretty much ignore them and proceed - which means that after one thing's failed, you'll almost certainly get another failure. Rip out those try/catch blocks, and just let the exception propagate up. (Declare that your main method can throw IOException.)

people

See more on this question at Stackoverflow