繁体   English   中英

Java读取和编码大型二进制文件

[英]Java read and encode large binary file

面对读取和编码最大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();
}

以下代码段来自此处的其他响应。

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

任何帮助,将不胜感激。

您无法继续在小块上使用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点声望。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM