簡體   English   中英

為什么我的DataInputStream只讀取114個字節?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM