[英]Why is my DataInputStream only reading 114 bytes?
I'm trying to extract a file from my jar and copying it into the temp
directory. 我正在尝试从jar中提取文件并将其复制到
temp
目录中。 To read the file within the jar, I am using a DataInputStream
, to write the file in the temp directory, I am using a DataOutputStream
. 要读取jar中的文件,我使用
DataInputStream
,将文件写入temp目录中,我使用DataOutputStream
。
The file I am trying to extract has a file size of 310 kilobytes, my copied file only contains 114 bytes after I've called my method (this is also the number of bytes my method prints to the console). 我尝试提取的文件的大小为310 KB,在我调用我的方法后,我复制的文件仅包含114个字节(这也是我的方法打印到控制台的字节数)。
Here is my method: 这是我的方法:
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);
}
}
The file I am trying to copy is a .dll
, so it's binary data I'm dealing with. 我要复制的文件是
.dll
,因此它是我正在处理的二进制数据。
The question is why is this happening and what am I doing wrong? 问题是为什么会这样,我在做什么错?
This does not explain why your method stops so soon, but you need to take care of it or you will have an even stranger problem with the result data being completely garbled. 这不能解释为什么您的方法这么快就停止了,但是您需要注意它,否则您将遇到一个更加奇怪的问题,即结果数据完全乱码。
From the APi doc of DataInputStream.read(): 从DataInputStream.read()的APi文档中:
Reads some number of bytes from the contained input stream and stores them into the buffer array b.
从包含的输入流中读取一定数量的字节,并将其存储到缓冲区数组b中。 The number of bytes actually read is returned as an integer.
实际读取的字节数以整数形式返回。
You need to use that return value and call the write() method that takes and offset and length. 您需要使用该返回值,并调用采用了offset和length的write()方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.