I am trying to write a method that makes a \"log.txt file\" if one does not already exist and then writes to the file. The problem that I am encountering is every time I cal
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);
}
You can change your PrintWriter and use method getAbsoluteFile(), this function returns the absolute File object of the given abstract pathname.
PrintWriter out = new PrintWriter(new FileWriter(log.getAbsoluteFile(), true));
Here is a simple example of how it works, best practice to put a try\catch into it but for basic use this should do the trick. For this you have a string and file path and apply thus to the FileWriter and the BufferedWriter. This will write "Hello World"(Data variable) and then make a new line. each time this is run it will add the Data variable to the next line.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
String Data = "Hello World";
File file = new File("C:/Users/stuff.txt");
FileWriter fw = new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(Data);
bw.newLine();
bw.close();
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!!");
}
You can even use FileOutputStream
to get what you need. This is how it can be done,
File file = new File(Environment.getExternalStorageDirectory(), "abc.txt");
FileOutputStream fOut = new FileOutputStream(file, true);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("whatever you need to write");
osw.flush();
osw.close();