How to overwrite a file in Java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • naivewisdom
    New Member
    • May 2010
    • 2

    How to overwrite a file in Java

    I'm writing a program that needs to overwrite a file at the end of each usage. Currently, the program work as a whole, except at the end of each game, when the overwrite method(shown below) is called, the file is not overwritten unless the user goes to the file, where a pop up box asks if you want to overwrite the file. Is there a way I can either delete the file at the beginning of the method or make the file automatically be written over without asking the player? Here is my code for that method currently:

    Code:
    private File learningFile; //previously in code
    learningFile = new File("learningFile"); //previously in code
    
    public void overWriteLearning() 
     { 
      learningFile.delete();
      FileOutputStream fout;  
      try
      {
          fout = new FileOutputStream ("learningFile");
          int a;
       int b; 
       int c;
      
        for( a=0; a<4; a++)
        {
         for(b=0; b<6; b++)
         {
          for(c=0; c<8; c++)
          {
           new PrintStream(fout).println (learning[a][b][c]);
          }
          c=0;
         }
         b=0;
        }
          fout.close();  
      }
      // Catches any error conditions
      catch (IOException e)
      {
       System.err.println ("Unable to write to file");
       System.exit(-1);
      }
     }
  • Dheeraj Joshi
    Recognized Expert Top Contributor
    • Jul 2009
    • 1129

    #2
    Please try

    Code:
    fout = new FileOutputStream ("learningFile",false);
    BTW,
    Code:
    fout = new FileOutputStream ("learningFile");
    This should also overwrite the file. Probably i did not understood your question :)

    Regards
    Dheeraj Joshi

    Comment

    • jkmyoung
      Recognized Expert Top Contributor
      • Mar 2006
      • 2057

      #3
      Is there a particular reason why the learningFile.de lete(); call isn't working?
      Do you get any error when calling it?

      How is the player "going to the file" ? Do you have some sort of filechooser?

      I don't think we're seeing the correct part of the code.

      Comment

      Working...