• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Help writing data to a file

 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I want to add data to an already existing file, and I just want to add the data to the end of the list in a text file.
I've written this but it creates a new file each time and wipes out all the old data.



How do I add the data to an already existing file?
 
Marshal
Posts: 79179
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The only way I have ever found to add data to a text file is the old-fashioned way with a BufferedWriter and a FileWriter. Look closely in the FileWriter constructors where you find hints about appending.
Like most things there is something about it in the Java Tutorials.
Also see if you can find an example of closing the writers in a finally block. I am not sure I would use a PrintStream; look closely at its API documentation and it tells you why, but if I did use a PrintStream it would read something like this:The finally makes sure that the file is closed even if an Exception occurs in the while loop. It has to be surrounded by a try-catch because it may itself throw an Exception. The PrintStream is declared outside the try-catch otherwise it would go out of scope. If there is an Exception, the PrintStream reference may be null at the beginning of the finally, hence the if (out != null) test. A flush() call is not usually necessary; see what the API says about close().

And good luck with it
 
Check your pockets for water buffalo. You might need to use this tiny ad until locate a water buffalo:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic