![](/img/trans.png)
[英]Which way is the best to save file on external storage on Android?
[英]Android: Best way to save image at external Storage
當我嘗試在某些設備上保存圖像時,應用程序崩潰。 經過一番研究,我認為問題是imageRoot,但是我迷失了這么多解決方案……我認為問題在於獲取外部存儲路徑。 我用來測試我的應用程序的設備沒有任何SD卡,路徑為/mnt/sdcard/Pictures
,並且圖像已成功保存。 無論手機是否具有SD卡,我都希望它能正常工作。 感謝您的任何幫助。
imageRoot=new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "AppName");
private void saveImage() {
Bitmap bitmap = sqimage.getDrawingCache();
File image = new File(imageRoot, imageName);
if (image.exists()) {
image.delete();
}
try {
FileOutputStream output = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
output.flush();
output.close();
new SingleMediaFileConnector(getActivity().getApplicationContext(), image);
} catch (FileNotFoundException e) {
e.printStackTrace();
success = false;
} catch (IOException e) {
e.printStackTrace();
success = false;
}
}
有時getExternalStoragePublicDirectory
路徑不存在。 您需要檢查其存在。
try {
imageRoot=new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "AppName");
File image = new File(imageRoot, imageName);
// Make sure the Pictures directory exists.
imageRoot.mkdirs();
// Other stuffs here
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
有關更多詳細信息,請參見此處 。
[編輯]
可以使用另一種方法:
getExternalFilesDir(Environment.DIRECTORY_PICTURES);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.