为什么我的 DataInputStream 只读取 114 个字节?

Why is my DataInputStream only reading 114 bytes?

我正在尝试从我的 jar 中提取一个文件并将其复制到 temp 目录中。 要读取 jar 中的文件,我使用 DataInputStream,要将文件写入临时目录,我使用 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 文档:

Reads some number of bytes from the contained input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer.

您需要使用该 return 值并调用获取偏移量和长度的 write() 方法。