![](/img/trans.png)
[英]Is there a reason why DataInputStream.read() only reads the first few bytes of really big arrays (>100,000 bytes)?
[英]Why is my DataInputStream only reading 114 bytes?
我正在尝试从jar中提取文件并将其复制到temp
目录中。 要读取jar中的文件,我使用DataInputStream
,将文件写入temp目录中,我使用DataOutputStream
。
我尝试提取的文件的大小为310 KB,在我调用我的方法后,我复制的文件仅包含114个字节(这也是我的方法打印到控制台的字节数)。
这是我的方法:
private static void extractFile(String pathInJar, String fileToCopy) {
File outputFile = new File(System.getProperty("java.io.tmpdir") + "/LDEngine/"+fileToCopy);
boolean couldDirsBeCreated = outputFile.getParentFile().mkdirs();
if(couldDirsBeCreated && !outputFile.exists()) {
int x;
int actualBytesRead = 0;
byte[] tmpByteArray = new byte[4096];
try(
DataOutputStream output = new DataOutputStream(new FileOutputStream(outputFile));
DataInputStream in = new DataInputStream(LibLoader.class.getResourceAsStream("/libs/natives/"+pathInJar))
){
while((x=in.read(tmpByteArray)) != -1) {
output.write(tmpByteArray);
actualBytesRead += x;
}
} catch(Exception e) {
System.err.println("Fatal error: Could not write file!");
System.exit(1);
}
System.out.println(actualBytesRead);
}
}
我要复制的文件是.dll
,因此它是我正在处理的二进制数据。
问题是为什么会这样,我在做什么错?
这不能解释为什么您的方法这么快就停止了,但是您需要注意它,否则您将遇到一个更加奇怪的问题,即结果数据完全乱码。
从DataInputStream.read()的APi文档中:
从包含的输入流中读取一定数量的字节,并将其存储到缓冲区数组b中。 实际读取的字节数以整数形式返回。
您需要使用该返回值,并调用采用了offset和length的write()方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.