Java程序从CSV读取内容写入TXT无法完整输出问题求助
FileWriter写入文件不完整的解决方法
核心原因:
FileWriter默认使用缓冲区,若未正确刷新或关闭流,缓冲区中的剩余内容不会写入文件,导致输出中断。控制台打印正常是因为控制台输出无缓冲(或自动即时刷新)。解决方案1:使用try-with-resources自动关闭流
这是最安全的方式,JVM会在代码块结束后自动关闭流,同时刷新缓冲区:try (FileWriter writer = new FileWriter("output.txt")) { // 假设contentList是从CSV读取到的内容集合 for (String content : contentList) { writer.write(content + System.lineSeparator()); } } catch (IOException e) { e.printStackTrace(); }解决方案2:手动刷新+关闭流
如果无法使用try-with-resources,需在写入过程中定期刷新缓冲区,最后务必关闭流:FileWriter writer = null; try { writer = new FileWriter("output.txt"); int lineCount = 0; for (String content : contentList) { writer.write(content + System.lineSeparator()); lineCount++; // 每写100行刷新一次,避免缓冲区溢出或未写入 if (lineCount % 100 == 0) { writer.flush(); } } writer.flush(); // 最后一次刷新剩余内容 } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); // 关闭流释放资源 } catch (IOException e) { e.printStackTrace(); } } }额外排查点
检查写入逻辑中是否存在未捕获的异常,比如某行数据格式异常导致程序提前终止。可以在循环内添加异常捕获,定位具体出错的行:for (String content : contentList) { try { writer.write(content + System.lineSeparator()); } catch (IOException e) { System.err.println("写入行失败:" + content); e.printStackTrace(); } }
内容的提问来源于stack exchange,提问作者Paweł Piotrowski
相关产品推荐
相关产品推荐

