snn*_*dsm 16 java file-io append
我试图将一些信息附加到文本文件中,但该文件仅显示最后写入的元素.
有许多Engineers,但它只打印到文件中读取的最后一个元素.
例如:
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));
Run Code Online (Sandbox Code Playgroud)
Pet*_*rey 42
我没有看到你关闭文件的位置.我也没有看到你读什么.
我假设你想要附加到文件而不是每次都覆盖它.在这种情况下,您需要使用FileOutputStream的append选项,因为这不是默认行为.
PrintStream writetoEngineer = new PrintStream(
new FileOutputStream("Engineer.txt", true));
Run Code Online (Sandbox Code Playgroud)
BTW:e.toString() + " "几乎相同,e + " "只是如果e为null则不抛出异常.