0

So many examples for this question. I tried and still doesn't work. Test.txt file is created. But no data is written into the test.txt file. What is wrong with my code? I have permission in the Manifest file as

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

Code:

String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
        "/PrintFiles";
File file = new File(file_path+"/test.txt");
if (!file.exists()) {
   try {
    file.createNewFile();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
}

FileOutputStream fos = null;
try {
    fos = openFileOutput(file.getName(), Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

byte[] b = {65,66,67,68,69};
fos.write(b);
fos.flush();
fos.close();

2 Answers 2

3

Cause, you are creating file in SDCard but writing in Internal Storage. Try as follows...

String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
        "/PrintFiles";
File file = new File(file_path+"/test.txt");
if (!file.exists()) {
   try {
    file.createNewFile();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
}

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

byte[] b = {65,66,67,68,69};
fos.write(b);
fos.flush();
fos.close();
Sign up to request clarification or add additional context in comments.

1 Comment

Should be fos = new FileOutputStream(file);
2

From the doc openFileOutput will

Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist.

those files are under the.

data > data > your app id > files

but your file is not in internal folder its in external storage..

Change this line

fos = openFileOutput(file.getName(), Context.MODE_PRIVATE);

into

fos=new FileOutputStream(file);

And try..

1 Comment

+1 Perfect answer, I check OP's code in my pc, after your suggestion, It is writing well in file.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.