I have written the following code to write to a file on external storage:
public static BufferedWriter out;
private void createFileOnDevice(Boolean append) throws IOException {
File Root = Environment.getExternalStorageDirectory();
Log.d("File",Root.toString());
Root.setWritable(true);
Root.setReadable(true);
Log.d("File","Writable: " + Root.canWrite());
if(Root.canWrite()){
File LogFile = new File(Root, "/Android/DriverInterfaceSystem");
if(!LogFile.mkdirs()){
Log.d("File","Couldn't make directories");
}
LogFile = new File(LogFile, "/trace.txt");
Log.d("File",LogFile.toString());
try{
FileWriter LogWriter = new FileWriter(LogFile, true);
LogWriter.write("--- New Record ---");
out = new BufferedWriter(LogWriter);
} catch(IOException e){
Log.d("File","FileWriter failed");
}
out.write("New record");
}
}
I have set permissions in Manifest to WRITE_EXTERNAL_STORAGE.
I know that having both a FileWriter and BufferedWriter is redundant, but I was testing if it was just one of them that wouldn’t work.
When I run, the file is created in the correct location, but the program refuses to write either “– New Record –” or “New Record” to the file, the file is just empty.
Given that the file is created, it seems that I’m missing one really simple step, but I’m damned if I can see it. Any thoughts?
I think you have to call flush() for it to actually write to the file. I think just calling write(…) only adds it to the buffer to be written. Here a quick example of usage:
Hope this helps.