我導出文件的SD卡,但是,我面對一個FileNotFound異常(04-12 01:26:18.494: DEBUG/Carburant(4568): /mnt/sdcard/Carburant/alaa.peugeot.settings.dat/alaa.peugeot.settings.dat (Is a directory)
)這裏是代碼:FileNotFoundException異常android系統中的SD卡
try {
File sdCard = Environment.getExternalStorageDirectory();
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
Log.d("Carburant", "Sdcard can read/write !!");
mExternalStorageAvailable = mExternalStorageWriteable = true;
try {
final SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(context);
String fileName = context.getResources().getString(
R.string.fileName);
String fileDir = "" + preferences.getString("login", "")
+ "." + preferences.getString("marque", "") + ".";
File f2 = new File(context.getFilesDir(), fileDir
+ fileName);
String y = f2.getAbsolutePath();
Log.d("HI Export", y);
InputStream in = new FileInputStream(f2);
File dir = new File(sdCard.getAbsolutePath()
+ "/Carburant/");
String x = dir.getAbsolutePath();
Log.d("HI", x);
File file = new File(dir, fileDir + fileName);
file.mkdirs();
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
// out.flush();
in.close();
out.close();
Toast.makeText(context, "Export effectué",
Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException ex) {
Toast.makeText(context, "File Not found",
Toast.LENGTH_SHORT).show();
String x = ex.getMessage();
Log.d("Carburant", x);
} catch (IOException e) {
Toast.makeText(context, "Echec", Toast.LENGTH_SHORT).show();
}
}
// copyfile(nom,file.getAbsolutePath());
else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
Log.d("Carburant", "Sdcard only read !!");
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states,
// but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
} catch (Exception e) {
Log.d("CARBURANT", e.getMessage());
}
要將文件從/data/data/<package name>/fileDir+fileName
出口在SD卡中的目錄Carburant。
您的路徑連接看起來很可疑。我建議插入一些魔術字符串,看看是否能解決問題。在加入文件名和目錄時,我建議分別從第二個和第一個段的開始和結尾修剪所有的正斜槓字符,並在它們之間重新插入斜線。顯然這不會處理「..」,「〜」或「。」,這也是你可能想要考慮的。 – 2011-04-11 23:38:02
@計算機語言學家:不,「。」沒有問題。因爲我在其他類/活動中使用此文件並且沒有遇到任何問題。創作道路上存在着絕對的錯誤。 :\ – androniennn 2011-04-11 23:45:33
我不認爲這個消息可能更清楚:'/mnt/sdcard/Carburant/alaa.peugeot.settings.dat/alaa.peugeot.settings.dat(是一個目錄)'。更改'File file = new File(dir,fileDir + fileName); file.mkdirs();'到'File file = new File(dir,fileDir); file.mkdirs();文件=新文件(文件,文件名);'。這就是說你的代碼是一團糟 - 終於使用,並且不要使用1000個變量 – 2013-09-16 10:27:48