0

I am just a beginner in learning Android.I want to learn how to write a piece of text to a file in Android.

My code to write, on clicking a button looks like this:

write.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            FileOutputStream fos;
            try {
                fos = openFileOutput("filename", Context.MODE_PRIVATE);
                fos.write(data.getBytes());
                fos.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            tv.setText("Values saved");
        }
    });

When I execute this the FileNotFoundException is thrown in logcat. As far as I know a new file will be created if no file with such name exists.

The logcat message is:

> 05-14 08:37:55.085: W/System.err(281): java.io.FileNotFoundException: /data/data/com.example.myproject11/files/test (No such file or directory)
user3602058
  • 219
  • 4
  • 10
  • do you mean `context.openFileOutput` ? Read [this](http://stackoverflow.com/questions/3625837/android-what-is-wrong-with-openfileoutput) – Raptor May 14 '14 at 03:19
  • You have to create the file. Using the file.createNew() and ensure the directory exists..using dir.mkdirs(). And don't do it from the Main thread, start a new thread. – Alécio Carvalho May 14 '14 at 18:11
  • `/data/data/com.example.myproject11/files/test` is not `"filename"`. at least post code that is consistent with the error you are getting. – njzk2 May 14 '14 at 18:19

1 Answers1

0

First we should check, file is exists or not. Better you try:

File fileDir = new File("filepath");
    if (!fileDir.exists())
        fileDir.mkdirs();

    try {
        File file = new File(fileDir, "filename");
        FileOutputStream outputStream = new FileOutputStream(file);
        outputStream.write(data.getBytes());
        outputStream.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    tv.setText("Values saved");
  • do you know what `openFileOutput` does? – njzk2 May 14 '14 at 18:20
  • hi Chetan.Thanks for helping me...I tried as you suggested.But still the FileNotFoundException is thrown. 05-15 00:04:51.903: W/System.err(303): java.io.FileNotFoundException: /filepath/filename (No such file or directory) Please help me on this – user3602058 May 14 '14 at 18:38
  • May be your filepath is wrong. Ok tell me location where you want to save the file. – Chetan Urmaliya May 15 '14 at 03:36