2011-05-19 60 views
1

我想存儲該代碼的創建文件的指定位置(即SD卡/ myfiles的/文件/)Android的:如何在我的SD卡的地方寫文件

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

我是新來的Java和Android開發人員,非常感謝您的幫助! :)

回答

4

使用下面的代碼寫入文件中的SD卡

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():類返回你的SD卡的路徑

我希望它能幫助

KPBird

1

使用以下代碼...

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