将文件从内部存储复制到Android 6上的USB存储

时间:2016-05-11 15:21:30

标签: java android android-6.0-marshmallow

到目前为止,我可以通过编程方式将文件从手机的内存复制到连接到它的USB-OTG。我只需要授予root权限并编辑platform.xml。但现在我的设备(三星Galaxy S6 Edge +)已经更新到Android 6并使我的代码停止工作。 我每次尝试按照以前的方式复制文件时都会收到此错误:

  

由java.lang.RuntimeException引起:java.io.FileNotFoundException:/ mnt / media_rw / 4265-1803 / requiredfiles / Oculus / 360Photos / Pisos / Chalet Anna / R0010008.JPG:open failed:EACCES(Permission denied)< / p>

String from = Environment.getExternalStorageDirectory() + File.separator + getString(R.string.FOLDER_SDCARD);
String to = Utils.getUsbPath() + File.separator + getString(R.string.FOLDER_USB);

FileManager fileManager = new FileManager(getActivity(), from, to, false);
fileManager.execute(true);

我的getUsbPath函数

public static String getUsbPath() {
        String finalpath = null;
        try {
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec("mount");
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            String line;
            String[] patharray = new String[10];
            int i = 0;
            int available = 0;

            BufferedReader br = new BufferedReader(isr);
            while ((line = br.readLine()) != null) {
                String mount = new String();
                if (line.contains("secure"))
                    continue;
                if (line.contains("asec"))
                    continue;

                if (line.contains("fat")) {// TF card
                    String columns[] = line.split(" ");
                    if (columns != null && columns.length > 1) {
                        mount = mount.concat(columns[1] + "/requiredfiles");

                        patharray[i] = mount;
                        i++;

                        // check directory is exist or not
                        File dir = new File(mount);
                        if (dir.exists() && dir.isDirectory()) {
                            // do something here

                            available = 1;
                            finalpath = mount;
                            break;
                        } else {

                        }
                    }
                }
            }
            if (available == 1) {

            } else if (available == 0) {
                finalpath = patharray[0];
            }

        } catch (Exception e) {

        }
        return finalpath;
    }

我的FileManager.class

public class FileManager extends AsyncTask<Boolean, Integer, Boolean> {

    private Context context;
    private String from;
    private String to;
    private ProgressDialog progressDialog;
    private int filesCount=0;
    private int filesTotal=0;
    Boolean completed;
    Boolean move;
    MainActivity main;

    public static final String TAG = "FileManager";

    public FileManager(Context context, String from, String to, Boolean move) {
        this.context = context;
        this.from = from;
        this.to = to;
        this.move = move;
        this.main = (MainActivity) context;
    }

    @Override
    protected Boolean doInBackground(Boolean... params) {

        File source = new File(from);
        File target = new File(to);
        try {
            countFiles(source);
            copyDirectory(source, target);
            if (move) {
                deleteFiles(source);
            }
            completed = true;
        } catch (Exception error) {
            Log.e(TAG, "doInBackground", error);
            completed = false;
            try {
                throw error;
            } catch (IOException e) {
                e.printStackTrace();
            }
            throw new RuntimeException(error.toString());
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        if (move) {
            progressDialog.setMessage(context.getString(R.string.moving_files));
        } else {
            progressDialog.setMessage(context.getString(R.string.copying_files));
        }
        progressDialog.setIndeterminate(true);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        progressDialog.dismiss();
        if (completed) {
            if (move) {
                Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.move_completed), Snackbar.LENGTH_LONG).show();
            } else {
                Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.copy_completed), Snackbar.LENGTH_LONG).show();
            }
        } else {
            if (move) {
                Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.move_failed), Snackbar.LENGTH_LONG).show();
            } else {
                Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.copy_failed), Snackbar.LENGTH_LONG).show();
            }
        }
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(filesTotal);
        progressDialog.setProgress(filesCount);
    }


    private void copyDirectory(File sourceLocation, File targetLocation) throws IOException {

        if (sourceLocation.isDirectory()) {
            if (!targetLocation.exists()) {
                targetLocation.mkdirs();
            }

            String[] children = sourceLocation.list();
            for (int i = 0; i < sourceLocation.listFiles().length; i++) {
                copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]));
            }
        } else {
            if (!targetLocation.exists()) {
                filesCount++;
                publishProgress();
                InputStream in = new FileInputStream(sourceLocation);

                OutputStream out = new FileOutputStream(targetLocation);

                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                in.close();
                out.close();
                scanFile(targetLocation.getCanonicalPath(), false);
            }
        }
    }

    private void countFiles(File file) {
        if (file.isDirectory()) {
            String[] children = file.list();
            for (int i = 0; i < file.listFiles().length; i++) {
                countFiles(new File(file, children[i]));
            }
        } else {
            filesTotal++;
        }
    }

    public void deleteFiles(File folder) {
        if (folder.isDirectory()) {
            File[] list = folder.listFiles();
            if (list != null) {
                for (int i = 0; i < list.length; i++) {
                    File tmpF = list[i];
                    if (tmpF.isDirectory()) {
                        deleteFiles(tmpF);
                    }
                    tmpF.delete();

                    String path;
                    try {
                        path = tmpF.getCanonicalPath();
                    } catch (Exception error) {
                        Log.e(TAG, "", error);
                        path = tmpF.getAbsolutePath();
                    }
                    scanFile(path, true);
                }
            }
        }
    }

    private void scanFile(String path, final boolean isDelete) {
        try {
            MediaScannerConnection.scanFile(context, new String[] { path },
                    null, new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            if (isDelete) {
                                if (uri != null) {
                                    context.getContentResolver().delete(uri,
                                            null, null);
                                }
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

我该如何解决?

0 个答案:

没有答案