程序运行后不写入文件

时间:2016-05-18 13:15:23

标签: java save fileoutputstream jgrasp

所以我试图写一个文件用作以后访问的保存点,但我实际上无法写入该文件。我试图保存类的组件以便在下次打开和运行程序时访问,通过将带有PIV的字符串写入文件作为保存方法并使用扫描程序搜索标记在每行的开头以便稍后访问。到目前为止,我的代码实际上不会写入文件。它编译并运行正常,但文件在程序运行后显示未更改。

   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();
      }
   }

如果有人有办法修改代码,甚至更好的保存想法请告诉我,谢谢

1 个答案:

答案 0 :(得分:0)

您正在替换每个save中的nextLine值 改变这一行:

save = sc.nextLine();

到这一个:

save += sc.nextLine();

此外,在将FileWriter写入文件时,最好使用String
因为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()