如何让FileWriter不覆盖首行,而是将内容追加到新行?
解决FileWriter覆盖首行的问题
问题根源
你遇到的核心问题是FileWriter默认采用覆盖模式打开文件,每次调用new FileWriter("subOrder.txt")时,都会清空文件原有内容再写入——这就是为什么不管你加多少换行符,首行都会被新内容覆盖,换行符只会在空文件里添加空行。
解决方案
直接使用FileWriter的追加模式构造方法,同时在写入内容后添加换行符即可解决:
- 修改FileWriter初始化代码,加入第二个参数
true,表示以追加模式打开文件:
FileWriter orderTaker = new FileWriter("subOrder.txt", true);
- 写入内容时拼接换行符(推荐用
System.lineSeparator()适配不同操作系统):
orderTaker.write("6 inch Sub" + System.lineSeparator());
修改后的完整代码片段
if (sub.size.equals("1")) { sub.price = sub.price + 7.19; try { // 启用追加模式,避免覆盖原有内容 FileWriter orderTaker = new FileWriter("subOrder.txt", true); // 写入内容并自动换行 orderTaker.write("6 inch Sub" + System.lineSeparator()); orderTaker.close(); } catch(IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } }
进阶优化(用BufferedWriter)
如果需要写入大量内容,用BufferedWriter会更高效,写法类似:
try { BufferedWriter writer = new BufferedWriter(new FileWriter("subOrder.txt", true)); writer.write("6 inch Sub"); writer.newLine(); // 专门的跨平台换行方法 writer.close(); } catch(IOException e) { System.out.println("An error occurred."); e.printStackTrace(); }
内容的提问来源于stack exchange,提问作者Jack Rast
相关产品推荐
相关产品推荐

