I want to save information in a textfile I already created. At school we only learnt to create a new one and save information in it.
How can I acheive this?
Thanks in advance
By default, if you create a FileOutputStream
or FileWriter
, it will just overwrite the existing text file - so if that's what you want to do, you're fine already.
If you want to append to a file, use the overload of the constructors for either of those types which takes a boolean
parameter to indicate append/overwrite:
FileOutputStream output = new FileOutputStream("data.txt", true);
If you have been using FileWriter
, by the way, I'd advise you to stop doing so - instead use FileOutputStream
wrapped in an OutputStreamWriter
. This allows you to specify the encoding you want to use, instead of always using the platform default encoding.
FileWriter fw = FileWriter(new File(pathToFile), true);
fw.write(stringToWrite);