【发布时间】: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