我想做一個簡單的操作。在android中創建一個文件,但我不知道爲什麼。 android沒有創建這個文件。 Android在調試2和調試3之間停止。文件夾未創建。我不明白爲什麼。在Android中創建文件的問題
try {
File inventoryDir = new File(Environment.getExternalStorageDirectory()+"/ludovic");
String userfile = "/session.txt";
if (!inventoryDir.exists()){
inventoryDir.mkdirs();
Log.i("debug","debug 1");
}
File userFile = new File(inventoryDir, userfile);
Log.i("debug","file path "+userFile.getAbsolutePath());
Log.i("debug","debug 2");
FileWriter fw = new FileWriter(userFile);
Log.i("debug","debug 3");
BufferedWriter bw = new BufferedWriter(fw);
Log.i("debug","debug 4");
bw.write("teste d'ecriture");
Log.i("debug","debug 5");
bw.close();
Log.i("debug","debug 6");
Log.i("debug","enregistre");
} catch (IOException e) {
Log.i("debug","non enregistre");
e.printStackTrace();
}
我有測試此代碼
try { // catches IOException below
final String TESTSTRING = new String("Hello Android");
// ##### Write a file to the disk #####
/* We have to use the openFileOutput()-method
* the ActivityContext provides, to
* protect your file from others and
* This is done for security-reasons.
* We chose MODE_WORLD_READABLE, because
* we have nothing to hide in our file */
FileOutputStream fOut = openFileOutput("samplefile.txt",
MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(TESTSTRING);
/* ensure that everything is
* really written out and close */
osw.flush();
osw.close();
蒙山這段代碼,我沒有問題的創建文件,但如果我用Windows資源管理器搜索我沒有找到這個文件。在清單文件
EDITED
File inventoryDir = new File(Environment.getExternalStorageDirectory()+"/ludovic");
if (!(inventoryDir.exists())){
inventoryDir.mkdir();
}
也WRITE_EXTERNAL_STORAGE權限:
我使用該權限 \t <用途的許可機器人:名稱= 「android.permission.WRITE_EXTERNAL_STORAGE」/> \t <使用的許可機器人:名稱= 「android.permission.ACCESS_COARSE_LOCATION」/> \t <使用說明 - 權限android:name =「android.permission.ACCESS_FINE_LOCATION」/> \t –
Agriesean
您可以發佈Logcat內容,我們可以確切知道引發了什麼異常。 – Aloong
這是一個警告:java.io.FileNotFoundException:/mnt/sdcard/ludovic/session.txt(權限被拒絕)。 – Agriesean