开发者

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 n开发者_如何学Pythonew to java and android dev, many thanks for any help! :)


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.


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());
}                   
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜