2014-02-14 83 views
1

我一直在看這個網站過去3個小時左右。 How to copy files from 'assets' folder to sdcard?mp3未正確保存到sd;如何將mp3保存到SD卡?

這是最好的我可以拿出來,因爲我只是試圖一次複製一個文件。

InputStream in = null; 
OutputStream out = null; 

public void copyAssets() { 

    try { 
     in = getAssets().open("aabbccdd.mp3"); 
     File outFile = new File(root.getAbsolutePath() + "/testf0lder"); 
     out = new FileOutputStream(outFile); 
     copyFile(in, out); 
     in.close(); 
     in = null; 
     out.flush(); 
     out.close(); 
     out = null; 
    } catch (IOException e) { 
     Log.e("tag", "Failed to copy asset file: ", e); 
    } 

} 

private void copyFile(InputStream in, OutputStream out) throws IOException { 
    byte[] buffer = new byte[1024]; 
    int read; 
    while ((read = in.read(buffer)) != -1) { 
     out.write(buffer, 0, read); 
    } 
} 

我已經想出瞭如何創建文件並保存文本文件。 http://eagle.phys.utk.edu/guidry/android/writeSD.html

我寧願將一個mp3文件保存到SD卡而不是文本文件。

當我使用我提供的這段代碼時,我得到一個與aabbccdd.mp3文件大小相同的文本文檔。它不創建文件夾並保存.mp3文件。它將文本文檔保存在根文件夾中。當你打開它時,我會看到一大堆中文字母,但在英文頂部,我可以看到WireTap這兩個字。 WireTap Pro是我用來記錄聲音的程序,所以我知道.mp3正在通過。它只是不創建一個文件夾,然後像上面的.edu例子一樣保存文件。

我該怎麼辦?

+0

你確定這是一個文本文件?你用什麼來打開文件? Windows記事本有一個衆所周知的'錯誤',導致它檢測到一些「文本」文件爲Unicode,並顯示一切爲「中國」。 –

回答

0

我認爲你應該做這樣的事情 - [注:我用一些其他的格式,而MP3,但它在我的應用程序的多種格式的作品,所以我希望它會爲ü工作了。]

InputStream in = this.getAssets().open("tmp.mp3"); //give path as per ur app   
    byte[] data = getByteData(in); 

確保你的文件夾已經存在於路徑上,如果文件夾不存在,它將不能正確保存內容。

byteArrayToFile(data , "testfolder/tmp.mp3"); //as per ur sdcard path, modify it. 

現在的方法::

1)getByteData從輸入流 -

private byte[] getByteData(InputStream is) 
    {       
    byte[] buffer= new byte[1024]; /* or some other number */ 
    int numRead; 
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
    try{   
     while((numRead = is.read(buffer)) > 0) { 
      bytes.write(buffer, 0, numRead); 
     }   
     return bytes.toByteArray(); 
    } 
    catch(Exception e) 
    { e.printStackTrace(); }   
    return new byte[0];  
    } 

2)byteArrayToFile

public void byteArrayToFile(byte[] byteArray, String outFilePath){  
    FileOutputStream fos; 
    try { 
     fos = new FileOutputStream(outFilePath); 
     fos.write(byteArray); 
     fos.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    }   
    } 
+0

@losethequit這是否有幫助?或者你找到其他解決方案嗎? – Neha