java.io.FileInputStream 文件是在使用 XSSFWorkbook 调用 excel 阅读器时生成的

java.io.FileInputStream file is getting generated on calling excel reader using XSSFWorkbook

提问人:Sheena Tyagi 提问时间:10/4/2023 更新时间:10/4/2023 访问量:26

问:

我遇到了一个问题,每次将路径初始化为 XSSFWorkbook 时,都会在我项目的根文件夹中创建一个文件java.io.FileInputStream@51bde877(每次都是 51bde877 是随机数)。 示例代码如下:

       try {
            fis = new FileInputStream(path);
            if (path.endsWith(".xls")) {
                workbook = new HSSFWorkbook(fis);
            }
            if (path.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(path);
            }

            if (rowNum <= 0)
                return false;

            int index = workbook.getSheetIndex(sheetName);
            if (index == -1)
                return false;

            sheet = workbook.getSheetAt(index);

            int colNum = -1;
            row = sheet.getRow(0);
            for (int i = 0; i < row.getLastCellNum(); i++) {
                //   System.out.println(row.getCell(i).getStringCellValue().trim());
                if (row.getCell(i).getStringCellValue().trim().equals(colName))
                    colNum = i;
            }

            if (colNum == -1)
                return false;

            sheet.autoSizeColumn(colNum);
            row = sheet.getRow(rowNum - 1);
            if (row == null)
                row = sheet.createRow(rowNum - 1);

            cell = row.getCell(colNum);
            if (cell == null)
                cell = row.createCell(colNum);

            cell.setCellValue(data);

            //fis.close();

            fileOut = new FileOutputStream(String.valueOf(new FileInputStream(path)));

            workbook.write(fileOut);
            fileOut.flush();
            workbook.close();

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

我应该如何防止在我的项目中创建这些垃圾文件?

java selenium-webdriver apache-poi fileinputstream xssfworkbook

评论

1赞 Mark Rotteveel 10/4/2023
这毫无意义:这就是导致问题的原因。您当前正在创建文件输出流,并且作为文件名,您使用的是 的文件输入流,该流始终为 .您可能的意思是,如果文件仍然通过打开,则可能无法正常工作。new FileOutputStream(String.valueOf(new FileInputStream(path)));toString()"java.io.FileInputStream@<hashcode>"new FileOutputStream(path)fis
0赞 Sheena Tyagi 10/4/2023
@MarkRotteveel 感谢您的输入。我做了以下更改 fis.close();fileOut = 新 FileOutputStream(路径);工作簿.write(文件输出);文件Out.flush();工作簿.close();但现在我在 workbook.write(fileOut) 中收到 .apache.poi.POIXMLException: java.lang.NullPointerException;线。
0赞 Mark Rotteveel 10/4/2023
我建议首先尝试使用不同的文件名进行写作,而无需关闭。POI 完全有可能无法写回同一个文件(我已经有一段时间没有使用它了),因为它需要保持打开状态,或者可能为此检查 POI 文档。fisfis

答: 暂无答案