【问题标题】:Large file to base64 string array大文件到base64字符串数组
【发布时间】:2015-12-07 22:26:01
【问题描述】:

由于我使用的文件很大,我的函数返回一个超出其限制的字符串。

有没有办法创建一个返回字符串数组的函数,以便以后我可以级联它们并重新创建文件?

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

【问题讨论】:

    标签: java android string base64 bytearray


    【解决方案1】:

    整部电影可能一次都无法放入 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 以开始使用输出流。

    【讨论】:

    • 如何将文件写入 1024 字节的块?另外,假设我将文件写入 1024 字节块,我还需要将每个块转换为 base-64 并将它们添加到服务器端,对吧?
    • +1 为您提供不错的答案 :) 是的,我正在将 base64 数据发布到 Web 服务,但我通过一次将总字符串发送给它来拨打电话。因此,如果可能的话,我更喜欢使用参数(比如说 mediaString[])。您推荐的就像将数据同步到 Web 服务,我更愿意在获得 mediaString[] 之后这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2016-12-03
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多