使用XSSFWorkbook操作Excel时生成垃圾文件的解决方法
解决XSSFWorkbook操作时生成java.io.FileInputStream@xxxx垃圾文件的问题
问题根源
垃圾文件的生成完全是因为你错误地将FileInputStream实例转成字符串作为输出文件名使用了。这行代码是直接诱因:
fileOut = new FileOutputStream(String.valueOf(new FileInputStream(path)));
当调用String.valueOf(new FileInputStream(path))时,实际是调用了FileInputStream的默认toString()方法,返回格式固定为java.io.FileInputStream@xxxx,程序会以此字符串作为文件名创建输出文件,也就是你看到的垃圾文件。
解决方案
- 直接使用原始文件路径
path作为输出流的目标路径,而非创建新的FileInputStream并转换为字符串。 - 使用try-with-resources语法自动管理输入输出流,避免手动关闭资源时出现泄漏问题。
修正后的完整代码
try (FileInputStream fis = new FileInputStream(path); FileOutputStream fileOut = new FileOutputStream(path)) { Workbook workbook = null; if (path.endsWith(".xls")) { workbook = new HSSFWorkbook(fis); } else if (path.endsWith(".xlsx")) { workbook = new XSSFWorkbook(fis); // 统一用流初始化,避免重复打开文件 } if (workbook == null || rowNum <= 0) { return false; } int index = workbook.getSheetIndex(sheetName); if (index == -1) { return false; } Sheet sheet = workbook.getSheetAt(index); int colNum = -1; Row row = sheet.getRow(0); if (row != null) { for (int i = 0; i < row.getLastCellNum(); i++) { Cell cell = row.getCell(i); if (cell != null && cell.getStringCellValue().trim().equals(colName)) { colNum = i; break; } } } if (colNum == -1) { return false; } sheet.autoSizeColumn(colNum); Row targetRow = sheet.getRow(rowNum - 1); if (targetRow == null) { targetRow = sheet.createRow(rowNum - 1); } Cell targetCell = targetRow.getCell(colNum); if (targetCell == null) { targetCell = targetRow.createCell(colNum); } targetCell.setCellValue(data); workbook.write(fileOut); fileOut.flush(); workbook.close(); } catch (Exception e) { e.printStackTrace(); return false; }
额外优化说明
- 修正输出流创建逻辑,直接用原路径写入(若需保留原文件,可先复制到临时文件,操作完成后替换)。
- 统一使用
FileInputStream初始化两种Workbook,避免重复打开文件。 - 添加空值判断(
row != null、cell != null),避免空指针异常。 - 用try-with-resources自动管理流资源,无需手动调用
close(),更安全可靠。
内容的提问来源于stack exchange,提问作者Sheena Tyagi
相关产品推荐
相关产品推荐

