Search code examples
androidfilelocation

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! :)


Solution

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