【问题标题】:Java read and encode large binary fileJava读取和编码大型二进制文件
【发布时间】:2014-04-27 01:31:38
【问题描述】:

面临读取和编码任何最大 100 MB 文件的问题。我的代码在小型 txt 文件和代码上工作得很好,可以处理大量数据。问题是最后一个由于未知原因无法正常工作。 尝试用谷歌搜索但没有运气,这就是我在这里的原因。

//Working snippet. Readind putty does nothing.
final String fileName = "C:\\putty.exe";
InputStream inStream = null;
BufferedInputStream bis = null;

try {
    inStream = new FileInputStream(fileName);
    bis = new BufferedInputStream(inStream);

    int numByte = bis.available();
    byte[] buf = new byte[numByte];

    bis.read(buf, 0, numByte);
    buf = Base64.encodeBase64(buf);
    for (byte b : buf) {
        out.write(b);
    }
} catch (Exception e) {
    e.printStackTrace();
} finally { 
    if (inStream != null)
        inStream.close();
    if (bis != null)
        bis.close();
}

以下 sn-p 来自此处的其他响应。

BufferedReader br = null;
long fsize;
int bcap;
StringBuilder sb = new StringBuilder();

FileChannel fc = new FileInputStream(fileName).getChannel();
fsize = fc.size();
ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fsize);
bb.flip();
bcap = bb.capacity();
while (bb.hasRemaining() == true) {
    bcap = bb.remaining();
    byte[] bytes = new byte[bcap];
    bb.get(bytes, 0, bytes.length);
    String str = new String(Base64.encodeBase64(bytes));            
    sb.append(str);
}
fc.close();
((DirectBuffer) bb).cleaner().clean();

String resultString = sb.toString();
out.write(resultString);
out.write("test");

这是我得到的例外

org.apache.jasper.JasperException: An exception occurred processing JSP page /read.jsp at line 57
54:         while (bb.hasRemaining() == true)
55:             bcap = bb.remaining();
56:             byte[] bytes = new byte[bcap];
57:             bb.get(bytes, 0, bytes.length);
58:             String str = new String(Base64.encodeBase64(bytes));            
59:             sb.append(str);
60:         fc.close();

任何帮助将不胜感激。

【问题讨论】:

  • 您总是使缓冲区与文件大小相同。 不要。对于大文件,您必须使用较小的缓冲区(可能是 8K,但要进行优化测试)并使用 CharsetEncoder 来流式传输数据。
  • @BoristheSpider 好的,知道了。第一个代码是概念验证,这就是为什么这么难看。期待一些提示如何使第二个工作。

标签: java file jsp binary base64


【解决方案1】:

您不能继续在小块上使用 base64,您以后将不知道如何对其进行解码,因为所有 base64 字符串组合将创建一个大的 base64 字符串,您将无法确定每个块的位置base64 字符串开始或结束。另外你无法预测base64字符串的大小

您必须立即在整个文件字节上创建 base64 字符串。

尝试替换

bb.get(bytes, 0, bytes.length);

bb.get(bytes, 0, bcap);

bb.get(bytes, 0, bb.remaining());

或许

byte[] bytes = new byte[bcap+1];

我无法评论我没有 50 声望。

【讨论】:

  • 尝试了所有建议,但没有成功。第一个丑陋而缓慢的解决方案有效,编码字节被正确解码。
猜你喜欢
  • 2014-12-19
  • 1970-01-01
  • 1970-01-01
  • 2016-09-20
  • 1970-01-01
  • 2021-07-26
  • 2011-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多