FileWriter意外停止

时间:2013-12-12 16:43:38

标签: java outputstream filewriter

我正在尝试使用XLS2CSV将Excel文件转换为csv文本文件。我稍微修改了现有的类以将PrintStream更改为Writer,因此我可以使用FileWriter写入文件。

无论如何,它写入System.out.PrintStream很好,一切都显示出来。但是当我打开文件时,最后几行丢失了。我的第一个假设是应用程序在完成写入之前关闭了连接,但是我使用无限循环来尝试测试,但即使让应用程序打开它也会做同样的事情。

有没有人有任何想法为什么这会打印到PrintStream正常但不写入文件?我将FileWriter更改为CSVWriter,它似乎写了更少的数据,所以我认为它确实与连接关闭有关,但我对输入和输出相当新,所以任何帮助都会受到赞赏。

这是一个功能示例(您需要修改输入和输出的文件名)

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


}

1 个答案:

答案 0 :(得分:4)

您没有关闭编写器,这意味着缓冲区中仍有数据。您应该在finally块中关闭它(以及所有其他流等),或者如果您使用的是Java 7,请使用try-with-resources语句。

另请注意,您当前“处理”异常的方式是几乎忽略它们并继续 - 这意味着在一件事失败后,您几乎肯定会再次失败。撕掉那些try / catch块,然后让异常传播起来。 (声明您的main方法可以抛出IOException。)