Search code examples
javadatainputstream

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. 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.

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).

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.

The question is why is this happening and what am I doing wrong?


Solution

  • 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():

    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.

    You need to use that return value and call the write() method that takes and offset and length.