將Android文件保存到外部存儲在創建一個目錄并在我的Android應用程序上將一個文件保存到它時,我遇到了一個小問題。我用這段代碼來做這件事:String filename = "MyApp/MediaTag/MediaTag-"+objectId+".png";File file = new File(Environment.getExternalStorageDirectory(),
filename);FileOutputStream fos;fos = new FileOutputStream(file);fos.write(mediaTagBuffer);fos.flush();fos.close();但它帶來了一個例外:java.io.FileNotFoundException:/mnt/sdCard/myApp/mediacard/mediacard-0.png(沒有此類文件或目錄)在這方面:fos = new FileOutputStream(file);如果我將文件名設置為:"MyApp/MediaTag-"+objectId+"它正在工作,但如果我試圖創建文件并將其保存到另一個目錄,則會拋出異常。你知道我做錯了什么嗎?還有另一個問題:是否有任何方法使我的文件在外部存儲中是私有的,這樣用戶就不能在圖片庫中看到它們,除非他將設備連接為Disk Drive?
3 回答
精慕HU
TA貢獻1845條經驗 獲得超8個贊
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
public boolean saveImageOnExternalData(String filePath, byte[] fileData) {
boolean isFileSaved = false;
try {
File f = new File(filePath);
if (f.exists())
f.delete();
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(fileData);
fos.flush();
fos.close();
isFileSaved = true;
// File Saved
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOException");
e.printStackTrace();
}
return isFileSaved;
// File Not Saved
}- 3 回答
- 0 關注
- 903 瀏覽
添加回答
舉報
0/150
提交
取消
