程序运行后未写入文件

File isn't written to after program runs

所以我正在尝试写入一个文件以用作稍后访问的保存点,但实际上我无法让它写入文件。我正在尝试保存 class 的组件以便下次打开和 运行 程序时访问,方法是将带有 PIV 的字符串作为保存方法写入文件并使用扫描仪来在每行的开头搜索标签以便稍后访问。到目前为止,我的代码实际上不会写入文件。它编译并且 运行s 很好,但是文件显示在程序 运行s 之后没有改变。

   public static void main(String[] args) throws FileNotFoundException, IOException
   {
      File f = new File("SaveFile");
      Scanner sc = new Scanner(f);
      String save = new String();
         while(sc.hasNextLine())
         {
                save=sc.nextLine();
         }
      byte buf[]=save.getBytes();
      FileOutputStream fos = new FileOutputStream(f);
      for(int i=0;i<buf.length;i++) 
        fos.write(buf[i]);
      if(fos != null)
      {
        fos.flush();
        fos.close();
      }
   }

如果有人有办法修复代码,或者有更好的保存方法,请告诉我,谢谢

您正在替换每个 nextLine 中的 save 值。
更改此行:

save = sc.nextLine();

给这个:

save += sc.nextLine();

此外,在将 String 写入文件时最好使用 FileWriter
并且由于 String 是 immutable,这将是一个缓慢的过程。考虑使用 StringBuilderCharBuffer 而不是我上面提到的简单解决方案。
查看下面包含的代码:

public static void main (String[] args) throws Exception
    {
        File f = new File("SaveFile");
        Scanner sc = new Scanner(f);
        StringBuilder builder = new StringBuilder();
        while (sc.hasNextLine())
        {
            builder.append(sc.nextLine() + "\n");
        }
        String save = builder.toString();
        FileWriter writer = new FileWriter(f);
        writer.write(save);
        writer.close();
    }

close() 隐式调用 flush().