2012-03-13 103 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

相關問題