2015-12-07 58 views
-1

由於我使用的文件很大,我的函數返回一個超出限制的字符串。大文件到base64字符串數組

有沒有辦法創建一個返回字符串數組的函數,以便稍後我可以級聯它們並重新創建該文件?

private String ConvertVideoToBase64() 
{ 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    FileInputStream fis; 

    try { 
     File inputFile = new File("/storage/emulated/0/Videos/out.mp4"); 

     fis = new FileInputStream(inputFile); 

     byte[] buf = new byte[1024]; 
     int n; 
     while (-1 != (n = fis.read(buf))) 
      baos.write(buf, 0, n); 
     byte[] videoBytes = baos.toByteArray(); 

     fis.close(); 

     return Base64.encodeToString(videoBytes, Base64.DEFAULT); 
     //imageString = videoString; 
    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 
} 

回答

2

整部電影大概在dooesn't適合在RAM中一次,這是什麼你想用你的baos對象做。

嘗試以這種方式重寫代碼,以便對每個1024字節的塊進行編碼,然後寫入文件/通過網絡發送/不管。

編輯:我認爲你需要使用流式方法。在您無法/不想一次保存所有數據的平臺上,這種情況很常見。

基本算法爲:

Open your file. This is an input stream. 
Connect to your server. This is your output stream 

While the file has data 
Read some amount of bytes, say 1024, from the file into a buffer. 
encode these bytes into a Base64 string 
write the string to the server 

Close server connection 
Close file 

你必須輸入流側。我假設你有一些你正在發佈的網絡服務。看看http://developer.android.com/training/basics/network-ops/connecting.html開始使用輸出流。

+0

如何將文件寫入1024字節的塊?另外,假設我將文件寫入1024字節塊,我還需要將每個塊轉換爲base-64並將它們添加到服務器端收集對嗎? – 0014

+0

編輯我的回答:) – MattD

+0

+1爲你的不錯的答案:)是的我發佈base64數據到一個Web服務,但我通過發送總字符串到一個電話一次。因此,如果可能的話,我寧願使用參數(比如說mediaString [])。你推薦的就像是將數據同步到一個Web服務,我寧願這樣做後獲得mediaString []。 – 0014