Domanda

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();
È stato utile?

Soluzione

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..

Altri suggerimenti

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();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top