文件写入 - PrintStream 追加 [英] File Write - PrintStream append

查看:28
本文介绍了文件写入 - PrintStream 追加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些信息附加到文本文件中,但该文件仅显示最后写入的元素.

I am trying to append some information into a text file, but the file only shows the last element written.

有很多 Engineer,但它只将读取的最后一个元素打印到文件中.

There are many Engineers, but it prints to the file only the last element which is read.

例如:

Engineer e = new Engineer(firstName,surName,weeklySal);
PrintStream writetoEngineer = new PrintStream(new File ("Engineer.txt"));

//This is not append. Only print. Overwrites the file on each item.
writetoEngineer.append(e.toString() + " "  + e.calculateMontly(weeklySal));

推荐答案

我没有看到您关闭文件的位置.我也没有看到你在阅读任何东西.

I don't see where you are closing the file. I don't see you reading anything either.

我假设您想附加到文件而不是每次都覆盖它.在这种情况下,您需要使用 FileOutputStream 的 append 选项,因为这不是默认行为.

I assume you want to append to the file instead of overwriting it each time. In that case you need to use the append option of FileOutputStream as this is not the default behaviour.

PrintStream writetoEngineer = new PrintStream(
     new FileOutputStream("Engineer.txt", true)); 

顺便说一句:e.toString() + " " 几乎与 e + " " 相同,只是如果 e 为空,它不会抛出异常.

BTW: e.toString() + " " is almost the same as e + " " except it doesn't throw an exception if e is null.

这篇关于文件写入 - PrintStream 追加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆