Kris
Kris

Reputation: 3769

Android: How to specify location of writing a file

I want to store the created file of this code somewhere in my sdcard (i.e. sdcard/myfiles/file/)

    final String TESTSTRING = new String("Hello Android");

    FileOutputStream fOut = openFileOutput("samplefile.txt", MODE_WORLD_READABLE);
    OutputStreamWriter osw = new OutputStreamWriter(fOut); 

    osw.write(TESTSTRING);

    osw.flush();
    osw.close();

I'm new to java and android dev, many thanks for any help! :)

Upvotes: 1

Views: 2616

Answers (2)

user756706
user756706

Reputation:

Use following code to write file in SDCard

try {
    File root = Environment.getExternalStorageDirectory();
    if (root.canWrite()){
        File gpxfile = new File(root, "samplefile.txt");
        FileWriter gpxwriter = new FileWriter(gpxfile);
        BufferedWriter out = new BufferedWriter(gpxwriter);
        out.write("Hello world");
        out.close();
    }
} catch (IOException e) {
    Log.e(TAG, "Could not write file " + e.getMessage());
}

Environment.getExternalStorageDirectory() class returns the path of your sdcard.

Upvotes: 4

Sujit
Sujit

Reputation: 10622

Use the following code ...

try {
File root = Environment.getExternalStorageDirectory()+"/myfiles/file/";
if (root.canWrite()){
    File gpxfile = new File(root, "gpxfile.gpx");
    FileWriter gpxwriter = new FileWriter(gpxfile);
    BufferedWriter out = new BufferedWriter(gpxwriter);
    out.write("Hello world");
    out.close();
}
} catch (IOException e) {
    Log.e(TAG, "Could not write file " + e.getMessage());
}                   

Upvotes: 1

Related Questions