Results 1 to 4 of 4
  1. #1
    counterfox is offline Member
    Join Date
    Mar 2009
    Posts
    45
    Rep Power
    0

    Default Writing to a file

    Hi i'm doing an assignment where I got to write data to a text file. I can do this but I'm doing the method which calls this in a while loop and when a String is written to a file needs to be saved, each time the data is written to file it keeps overwriting the line before, my codes below:

    Java Code:
    String data = "this is the data I want to write on this method call";
    String filename = "save.sav";
    try {
    FileWriter writer = new FileWriter(filename);
    writer.write(data);
    writer.close();
    }
    catch (IOException e){}
    This is in a method call but whenever I call the method again the old data is overwritten. Is there a way to change this so it saves the text on a new line?

    Thanks.

  2. #2
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    786
    Rep Power
    5

  3. #3
    Allspark is offline Member
    Join Date
    Sep 2010
    Posts
    21
    Rep Power
    0

    Default

    The error I see in your code is that you're declaring the new output file in the loop. So every time the loop iterates, it will create a new file with the same name and will therefore replace the previous one. In order for it to work you have to declare your output file outside of the loop and then just print to the output file within the loop. So for example:
    Java Code:
    String data = "this is the data I want to write on this method call";
    String filename = "save.sav";
    [COLOR="Red"]FileWriter writer = new FileWriter(filename);[/COLOR]
    try {
    writer.write(data);
    }
    [COLOR="Red"]writer.close();[/COLOR]
    catch (IOException e){}
    So this declares the file outside of the loop, executes the loop and writes the data to the output file, exits the loop and then closes the output file.
    - Winners compare their achievements with their goals, while losers compare their achievements with those of other people. -

  4. #4
    counterfox is offline Member
    Join Date
    Mar 2009
    Posts
    45
    Rep Power
    0

    Default

    Thanks for your reply I didnt see I was doing that,

    Thanks again for your help =]

Similar Threads

  1. reading a file and writing to a file....help!!!!
    By java_prgr in forum New To Java
    Replies: 3
    Last Post: 07-26-2010, 06:53 PM
  2. Replies: 1
    Last Post: 02-27-2010, 01:29 AM
  3. Replies: 9
    Last Post: 10-20-2009, 10:52 AM
  4. Replies: 3
    Last Post: 05-09-2009, 11:31 PM
  5. Replies: 9
    Last Post: 07-10-2008, 04:52 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •