如何在Android上将文件从SD复制到本地存储

时间:2015-10-19 03:20:31

标签: java android copy android-4.4-kitkat

我知道Kit Kat只能写入SD卡上的应用程序包特定目录。然而,我的印象是你仍然可以通过以下方式将文件从SD卡复制到本地存储:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

我只是测试我是否可以复制一个文件。如果我能够这样做,我将添加代码来搜索整个SD卡DCIM文件夹。现在我有以下代码(请原谅代码的混乱,我写了C#和vb.net,但java对我来说还是一个新东西):

String dirPath = getFilesDir().getAbsolutePath() + File.separator + "TCM";
            File projDir = new File(dirPath);
            if (!projDir.exists())
                projDir.mkdirs();
            String CamPath = projDir + File.separator + tv2.getText();
            File projDir2 = new File(CamPath);
            if (!projDir2.exists())
                projDir2.mkdirs();
            File LocalBuck = new File(projDir2 + File.separator );

            String imageInSD = Environment.getExternalStorageDirectory().getAbsolutePath();
            File directory1 = new File (sdCard.getAbsolutePath() + "/DCIM");
            File directory = new File(directory1 + "/100SDCIM");
            File Buckfile = new File(directory, "/BigBuck.jpg");


            try {
                exportFile(Buckfile, LocalBuck);
            } catch (IOException e) {
                e.printStackTrace();
            }

以下是导出功能/应用程序的代码:

 private File exportFile(File src, File dst) throws IOException {

     //if folder does not exist
     if (!dst.exists()) {
         if (!dst.mkdir()) {
             return null;
         }
     }

     String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HHmmss").format(new Date());
     File expFile = new File(dst.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
     FileChannel inChannel = null;
     FileChannel outChannel = null;

     try {
         //Straight to Error Handler
         inChannel = new FileInputStream(src).getChannel();
         outChannel = new FileOutputStream(expFile).getChannel();
     } catch (FileNotFoundException e) {
         e.printStackTrace();
     }

     try {
         inChannel.transferTo(0, inChannel.size(), outChannel);
     } finally {
         if (inChannel != null)
             inChannel.close();
         if (outChannel != null)
             outChannel.close();
     }

     return expFile;
 }

以下是我的模拟器的样子: 寻找:Debug of SD Location

应该找到它?:EmulatorShowingSd

问题:我甚至可以在KitKat之后将文件从SD卡复制到本地存储;如果是这样导致在尝试访问SD卡文件时引发异常的代码有什么问题?

0 个答案:

没有答案