2012-03-13 98 views
0

我拼命试图从我的原始文件夹复制文件到SD卡,但它不会工作!该文件只是不显示在文件管理器中,我给出的路径(通过意图)的程序也找不到它。这就是我想...将文件复制到SD卡

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(); 
    } 
+1

你给使用许可权android.permission.WRITE_EXTERNAL_STORAGE每@SadeshkumarPeriyasamy的评论 – 2012-03-13 09:36:30

+0

检查权限。另外,尝试通过使用'FileOutputStream out = new FileOutputStream(new File(Environment.getExternalStorageDirectory(),“/jazz.pdf”))创建输出路径' – 2012-03-13 09:39:25

+0

@SadeshkumarPeriyasamy是的,我有!在我的Android清单中: user1123530 2012-03-13 09:40:04

回答

2

只要写在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(); 
    } 
} 
+0

非常感谢! :)解决了它。 – user1123530 2012-03-13 09:49:55