Write to text file without overwriting in Java
For some reason, none of the other methods worked for me...So i tried this and worked. Hope it helps..
JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file\n hi \n hello \n hola";
try
{
RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
long length = raf.length();
System.out.println(length);
raf.setLength(length + 1); //+ (integer value) for spacing
raf.seek(raf.length());
raf.writeBytes(Content);
raf.close();
}
catch (Exception e) {
System.out.println(e);
}
Just change PrintWriter out = new PrintWriter(log);
to
PrintWriter out = new PrintWriter(new FileWriter(log, true));
use a FileWriter instead.
FileWriter(File file, boolean append)
the second argument in the constructor tells the FileWriter to append any given input to the file rather than overwriting it.
here is some code for your example:
File log = new File("log.txt")
try{
if(!log.exists()){
System.out.println("We had to make a new file.");
log.createNewFile();
}
FileWriter fileWriter = new FileWriter(log, true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("******* " + timeStamp.toString() +"******* " + "\n");
bufferedWriter.close();
System.out.println("Done");
} catch(IOException e) {
System.out.println("COULD NOT LOG!!");
}