【问题标题】:Copying a file to sdcard将文件复制到 SD 卡
【发布时间】:2012-03-13 09:30:44
【问题描述】:

我正在拼命尝试从我的原始文件夹中将文件复制到 sdcard,但它不起作用!该文件只是没有显示在文件管理器中,而且我(通过意图)提供路径的程序也找不到它。这就是我正在尝试的...

private void CopyAssets() throws IOException {
        String path = Environment.getExternalStorageDirectory() + "/jazz.pdf";
        InputStream in = getResources().openRawResource(R.raw.jazz);
        FileOutputStream out = new FileOutputStream(path);
        byte[] buff = new byte[1024];
        int read = 0;
    try {
       while ((read = in.read(buff)) > 0) {
          out.write(buff, 0, read);
       }
    } finally {
         in.close();

         out.close();
    }
}

之后我尝试...

    try {
        CopyAssets();

    } catch (IOException e1) {
        e1.printStackTrace();
    }

    String aux = Environment.getExternalStorageDirectory() + "/jazz.pdf";

    Uri path = Uri.parse(aux);

    Intent intent = new Intent(Intent.ACTION_VIEW);

    intent.setDataAndType(path, "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    try {

        startActivity(intent);

    } catch (ActivityNotFoundException e) {

        Toast.makeText(bgn1.this, "No Application Available to View PDF",
                Toast.LENGTH_SHORT).show();
    }

【问题讨论】:

  • 你有没有给使用权限android.permission.WRITE_EXTERNAL_STORAGE
  • 根据@SadeshkumarPeriyasamy 的评论检查权限。另外,尝试使用FileOutputStream out = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "/jazz.pdf")) 创建输出路径
  • @SadeshkumarPeriyasamy 是的,我有!在我的 android 清单中:
  • @AleksG 这基本上是一样的,但我试过了,它仍然不起作用......我的模拟器有问题吗?我真的看不出这有什么问题。
  • 另外,关闭输出文件后,用File.isFile检查是否存在

标签: android file sd-card


【解决方案1】:

只需在 finally 块中写 out.flush(); 并让我知道发生了什么,

finally {
       out.flush();
       in.close();
       out.close();
      }

更新:

工作代码:

private void CopyAssets() throws IOException
{       
    InputStream myInput = getResources().openRawResource(R.raw.jazz);
    String outFileName = Environment.getExternalStorageDirectory() + "/jazz.pdf";
    OutputStream myOutput = new FileOutputStream(outFileName);
    // transfer bytes from the input file to the output file
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0)
    {
        myOutput.write(buffer, 0, length);
    }
    // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多