我想創(chuàng)建一個.txt文件并將其存儲在Android手機(jī)的外部存儲器。我增加了Android Manifest權(quán)限。我運(yùn)行代碼時不給出任何錯誤提示,但文件卻創(chuàng)建不了。我不知道代碼哪里出錯,請高人指點(diǎn),謝謝。public void createExternalStoragePrivateFile(String data) {
// Create a path where we will place our private file on external
// storage.
File file = new File(myContext.getExternalFilesDir(null), "state.txt");
try {
FileOutputStream os = null;
OutputStreamWriter out = null;
os = myContext.openFileOutput(data, Context.MODE_PRIVATE);
out = new OutputStreamWriter(os);
out.write(data);
os.close();
if(hasExternalStoragePrivateFile()) {
Log.w("ExternalStorageFileCreation", "File Created");
} else {
Log.w("ExternalStorageFileCreation", "File Not Created");
}
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
3 回答

慕勒3428872
TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個贊
File file = new File(myContext.getExternalFilesDir(null), "state.txt");
try {
FileOutputStream os = new FileOutputStream(file, true);
OutputStreamWriter out = new OutputStreamWriter(os);
out.write(data);
out.close();
}

森林海
TA貢獻(xiàn)2011條經(jīng)驗(yàn) 獲得超2個贊
你需要添加一個正確的權(quán)限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

莫回?zé)o
TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個贊
我之前也遇見過這個問題,用這段代碼能實(shí)現(xiàn):
public void createExternalStoragePrivateFile(String data) { // Create a path where we will place our private file on external // storage. File file = new File(myContext.getExternalFilesDir(null), "state.txt"); try { FileOutputStream os = new FileOutputStream(file); OutputStreamWriter out = new OutputStreamWriter(os); out.write(data); out.close(); if(hasExternalStoragePrivateFile()) { Log.w("ExternalStorageFileCreation", "File Created"); } else { Log.w("ExternalStorageFileCreation", "File Not Created"); } } catch (IOException e) { // Unable to create file, likely because external storage is // not currently mounted. Log.w("ExternalStorage", "Error writing " + file, e); } }
添加回答
舉報
0/150
提交
取消