eskimo9
eskimo9

Reputation: 753

Android application write to sdcard files

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?

Upvotes: 0

Views: 1808

Answers (2)

Alex Lockwood
Alex Lockwood

Reputation: 83303

You forgot to call flush() and close() on your FileWriter.


Edit #1:

I'd also like to point out that the following code is unnecessary:

root.setWritable(true);
root.setReadable(true);

The call to getExternalStorageDirectory() returns a readable/writable File by default (assuming you've given your application the proper permissions).


Edit #2:

Last thing. Please make sure that before you do any work with the external storage, you always call getExternalStorageState() to check whether the media is available. The media might be mounted to a computer, missing, read-only, or in some other state. See the documentation for more information.

Upvotes: 2

Bradford2000
Bradford2000

Reputation: 723

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:

FileWriter fWriter;
try{
    fWriter = new FileWriter(“\sdcard\filename.txt”);
    fWriter.write(yourString);
    fWriter.flush();
    fWriter.close();
}catch(Exception e){
    e.printStackTrace();
}

Hope this helps.

Upvotes: 1

Related Questions