2015-12-07 61 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