文件写入 - PrintStream附加

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则不抛出异常.

  • @Mert:`File`没有构造函数,你可以在其中指定像Peter使用的`FileOutputStream`构造函数一样追加.显然如果你在后者中指定`false`,它就不会追加.`File`和`FileOutputStream`有什么区别?他们是完全不相交的.当你将`File`传递给`PrintStream`时,它会在引擎盖下创建一个`FileOutputStream`,但是在非追加模式下.它只是为了方便起见.类似地,您可以将`File`传递给`FileOutputStream`,但为方便起见它也需要一个String. (2认同)