0

我正在尝试将整个目录复制到 USB 存储:

  File Sdfile = new File(Environment.getExternalStorageDirectory(), "myfolder");

                Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);

                intent.setType("*/*");
                 intent.setType(DocumentsContract.Document.MIME_TYPE_DIR);//For API 19+
                 intent.putExtra(Intent.EXTRA_TITLE, Sdfile.getName());
                intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
                startActivityForResult(intent, 47);


  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {


        if (requestCode == 47) {
            if (resultCode != RESULT_OK) return;
            File file = new File(Environment.getExternalStorageDirectory(), "myfolder");
             copyFile(file, data.getData());

        }

下面的代码用于将整个文件夹复制到 USB 存储。

  private void copyFile(File src, Uri destUri) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            bis = new BufferedInputStream(new FileInputStream(src));
            bos = new BufferedOutputStream(getContentResolver().openOutputStream(destUri));
            byte[] buf = new byte[5024];
            bis.read(buf);
            do {
                bos.write(buf);
            } while (bis.read(buf) != -1);
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) bis.close();
                if (bos != null) bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

当我试图复制整个文件夹时,它会出错。

即使我直接将整个文件夹复制到 USB 存储。

我怎样才能复制整个目录?

4

1 回答 1

0

I'm guessing your app does not have the correct permissions. For Android versions below KitKat, you need to declare the permission WRITE_EXTERNAL_STORAGE in your AndroidManifest.xml

<user-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Reference: http://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE

于 2016-03-23T09:30:03.490 回答