Dennis
Dennis

Reputation: 143

Problems writing to a file

I am trying to write to a file in an Android app with this code:

File save = new File("sdcard/save.txt"); 
if(!save.exists()) {
    try {
        save.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

try {
    FileOutputStream fos = new FileOutputStream(save);
    OutputStreamWriter osw = new OutputStreamWriter(fos);

    osw.write("1");
    osw.flush();
    osw.close();
} catch (FileNotFoundException e1) {
    e1.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

However, my debugger goes to the IOException after the line osw.close();

The problem is by that stage e doesn't exist, so I cant read the exception message.

I added the right premission in the androidManifest.xml

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

but it doesn't work.

Upvotes: 1

Views: 178

Answers (3)

Chaitu
Chaitu

Reputation: 917

I think you need to give the permission in manifest.xml.

Upvotes: 0

Tobias Moe Thorstensen
Tobias Moe Thorstensen

Reputation: 8981

I have recently written a file to my sdcard this way:

private static final String sdcardPath = "/mnt/sdcard/yourfolder_or_fileName"
File folder = new File(path);

But you should use, as mentioned above, this solution

String path= Environment.getExternalStorageDirectory().getAbsolutePath();

Upvotes: 0

Samir Mangroliya
Samir Mangroliya

Reputation: 40406

 File save = new File("sdcard/save.txt"); is bad code   

use below code

String path= Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";

File file = new File(path + File.separator + fileName);

Upvotes: 2

Related Questions