【问题标题】:How to copy image to an existing directory on sd card?如何将图像复制到 sd 卡上的现有目录?
【发布时间】: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)中授予权限。

编辑:

  1. 建议在fileOutputStream 之前创建文件(没有帮助)。

  2. 降低了 targetSdkVersion 以解决与权限相关的任何可能问题,但仍然没有成功。

targetSdkVersion 22

  1. 以这种方式创建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


    【解决方案1】:

    你需要先创建文件,如果文件不存在FileOutputStream会抛出异常FileNotFoundException

    File outputFile = new File(outPath);
    file.createNewFile();
    fileOutputStream = new FileOutputStream(outputFile);
    

    【讨论】:

    • open failed: EACCES (Permission denied)
    • 试过你的答案,但没有帮助。
    【解决方案2】:

    如果您在您的应用程序 gradle 文件中使用targetSdkVersion 23(或更高版本),则需要显式请求权限(可以在 Activity 的 onCreate 方法或按钮侦听器方法中),如下所示...

    private static final int CODE_WRITE_EXTERNAL = 10;
        if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        Log.d(TAG, "onCreate: " + "Show explanation");
                        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE_WRITE_EXTERNAL );
                    } else {
                        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE_WRITE_EXTERNAL );
                    }
                } else {
                    Log.d(TAG, "onCreate: " + "Permission already granted!");
                    //Call your method to save the file
                }
    

    那你需要实现下一个回调方法

    @Override
        public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
            switch (requestCode) {
                case CODE_WRITE_EXTERNAL : {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        Log.d(TAG, "onRequestPermissionsResult: Good to go!");
                        //Call your mehotd here
                    } else {
                        Log.d(TAG, "onRequestPermissionsResult: Bad user");
                    }
                }
            }
        }
    

    【讨论】:

    • 谢谢,但我已经实现了 sdk 23 及更高版本的读写权限请求,为了简单起见,决定不提它。这是错误的决定对不起。还是有问题。
    【解决方案3】:

    这就是我使用 SAF 完成工作的方式。

    private void newcopyFile(File fileInput, String outputParentPath,
                        String mimeType, String newFileName) {
    
    DocumentFile documentFileGoal = DocumentFile.fromTreeUri(this, treeUri);
    
    String[] parts = outputParentPath.split("\\/");
    for (int i = 3; i < parts.length; i++) { //ex: parts:{"", "storage", "extSdCard", "MyFolder", "MyFolder", "MyFolder"}
        if (documentFileGoal != null) {
            documentFileGoal = documentFileGoal.findFile(parts[i]);
        }
    }
    if (documentFileGoal == null) {
        Toast.makeText(MainActivity.this, "Directory not found", Toast.LENGTH_SHORT).show();
        return;
    }
    
    DocumentFile documentFileNewFile = documentFileGoal.createFile(mimeType, newFileName);
    
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
        outputStream = getContentResolver().openOutputStream(documentFileNewFile.getUri());
        inputStream = new FileInputStream(fileInput);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        if (outputStream != null) {
            byte[] buffer = new byte[1024];
            int read;
            if (inputStream != null) {
                while ((read = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, read);
                }
            }
            if (inputStream != null) {
                inputStream.close();
            }
            inputStream = null;
            outputStream.flush();
            outputStream.close();
            outputStream = null;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      相关资源
      最近更新 更多