FileWriter not writing to file in Android?
Asked Answered
C

2

5

I am trying to write to a new file named "filename.txt" and write out "hi" when I open an app. How do I go about this? I run this code in Eclipse, press F11, open up the AVD, and click on the app. I get the "Hello World, appname!" message, but no file is created.

package com.paad.comparison;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;

public class ComparisonOfControlCreationActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
        String string1 = "Hey you";
        FileWriter fWriter;
        try{
            fWriter = new FileWriter("filename.txt", true);
            fWriter.write("hi");
            fWriter.flush();
            fWriter.close();
        } catch(Exception e) {
            e.printStackTrace();
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

EDIT: For anyone that happens to run into this problem in the future, make sure your AndroidManifest.xml file has the following line in it:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Concatenate answered 8/7, 2012 at 20:27 Comment(2)
is there anything in the logcat when it runs?Piperine
For those who are relatively new and are debugging, just know that WRITE_EXTERNAL_STORAGE is not needed for API level 19 or higher. So if your app targets API level 21 (check your app/build.gradle), then permissions is not something you need to add to your AndroidManifest.xml sourceCoriolanus
P
7

Try like this:

FileWriter fWriter;
File sdCardFile = new File(Environment.getExternalStorageDirectory() + " \filename.txt");
Log.d("TAG", sdCardFile.getPath()); //<-- check the log to make sure the path is correct.
try{
     fWriter = new FileWriter(sdCardFile, true);
     fWriter.write("hi");
     fWriter.flush();
     fWriter.close();
 }catch(Exception e){
          e.printStackTrace();
 }
Piperine answered 8/7, 2012 at 20:54 Comment(3)
Thanks, Tim. That code runs; however, I still don't see the file being saved anywhere. Should there be a path that the .getExternalStorageDirectory() refers to? Would this only run correctly on a hardware device?Concatenate
I would think it would work on emulator, but honestly I don't know. I only use the emulator to test different screen sizes. Everything else I test on devices.Piperine
@MiguelDiaz does your emulator have SD card setup?Size
C
3

You need to call sync() before closing the file, but you need a FileDescriptor for that, and I don't believe it's available directly from FileWriter. However, you can create a FileWriter object using a FileDescriptor, and FileOutputStream can provide one for this purpose.

The following is based on your initial code, but I've opted to store the file on the sdcard in my example, so to run the code below as is your app manifest will need the correct permission added prior to the <application> tag.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

That said, the outcome won't be affected if you want store the file on the device directly.

Code (tested on a Desire HD):

package com.paad.comparison;

import java.io.FileOutputStream;
import java.io.FileWriter;

import android.app.Activity;
import android.os.Bundle;

public class ComparisonOfControlCreationActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        String string1 = "Hey you";

        FileOutputStream fos ;

        try {
            fos = new FileOutputStream("/sdcard/filename.txt", true);

            FileWriter fWriter;

            try {
                fWriter = new FileWriter(fos.getFD());
                fWriter.write("hi");
                fWriter.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                fos.getFD().sync();
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Finally, as flush() is called by close(), calling flush() immediately prior to close() is superfluous, though not harmful.

Cowart answered 12/7, 2012 at 16:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.