FileWriter not writing to file in Android?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-05 21:05:01

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();
 }

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!