Search code examples
javasavefileoutputstreamjgrasp

File isn't written to after program runs


So i'm trying to write to a file to use as a save point to access later, but i cant actually get it to write to the file. I'm trying to save the components of a class to access next time I open and run the program, by writing a string with the PIV's to the file as a save method and by using a scanner to search for tags at the beginning of each line to access later. My code so far though, will not actually write to the file. It compiles and runs fine, but the file shows being unchanged after the program runs.

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

If anyone has a way to fix the code or even a better idea for saving please let me know, thanks


Solution

  • You are replacing save value in every single nextLine.
    Change this line:

    save = sc.nextLine();
    

    to this one:

    save += sc.nextLine();
    

    Also, it's better to use a FileWriter when you are writing String to a file.
    And because String is immutable, it will be a slow procedure. Consider using StringBuilder or CharBuffer instead of simple solution which I mentioned above.
    Look at code included below:

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

    Also close() implicitly calls flush().