【发布时间】:2016-11-21 13:51:30
【问题描述】:
我正在尝试使用以下代码复制图像文件:
InputStream fileInputStream = null;
OutputStream fileOutputStream = null;
String inPath = "/storage/emulated/0/Pictures/MyImage.jpg";
String outPath = "/storage/extSdCard/MyFolder/MyImage.jpg";
try {
verifyStoragePermissions(this);
fileInputStream = new FileInputStream(new File(inPath));
File outputFile = new File(outPath);
if (!outputFile.exists()) {
try {
outPutFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
fileOutputStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, read);
}
fileInputStream.close();
fileInputStream = null;
fileOutputStream.flush();
fileOutputStream.close();
fileOutputStream = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
这就是在sdk上验证存储权限的方法>=23
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
/**
* Checks if the app has permission to write to device storage
*
* If the app does not has permission then the user will be prompted to grant permissions
*
* @param activity
*/
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
结果是在到达buffer 行之前发生此错误。
Unable to decode stream: java.io.FileNotFoundException: /storage/extSdCard/MyFolder/MyImage.jpg: open failed: ENOENT (No such file or directory)
我的 SD 卡上有 MyFolder,我的设备上的图库应用程序将图像复制到此目录没有任何问题。
注意:在清单中(在应用程序标记之前的正确位置)和内部活动(对于 skd >=23)中授予权限。
编辑:
建议在
fileOutputStream之前创建文件(没有帮助)。降低了 targetSdkVersion 以解决与权限相关的任何可能问题,但仍然没有成功。
targetSdkVersion 22
-
以这种方式创建
File:File outFile = new File("/storage/extSdCard", "MyFolder/MyImage.jpg");也没有结果。
我正在 android 版本 22 上测试它。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
【问题讨论】:
标签: android android-sdcard fileoutputstream file-copying