簡體   English   中英

用Java讀取二進制文件

[英]Reading a binary file in Java

我有一個相對較長的無符號整數文件(每個64位,0.47GB文件),我需要讀取並存儲在一個數組中。 經過一段時間的腦力勞動后,我終於使用了這種類型,因為Java中的所有內容都已簽名(請糾正我,如果我錯了,請),我想不出更好的選擇。 無論如何,只需要對數組進行排序,因此原始數字的精確值並不是最重要的。 我們應該測量排序算法的效率,僅此而已。 然而,當我真正來閱讀文件時,我遇到了一堵磚牆(我的代碼如下)。

public class ReadFileTest {
    public static void main(String[] args) throws Exception {
        String address = "some/directory";
        File input_file = new File (address);
        FileInputStream file_in = new FileInputStream(input_file);
        DataInputStream data_in = new DataInputStream (file_in );

        long [] array_of_ints = new long [1000000];
        int index = 0;

        long start = System.currentTimeMillis();

        while(true) {
            try {
                long a = data_in.readLong();
                index++;
                System.out.println(a);
            }
            catch(EOFException eof) {
                System.out.println ("End of File");
                break;
            }
        }

        System.out.println(index);
        System.out.println(System.currentTimeMillis() - start);
    }
}

它會一直持續下去,我通常會在節目閱讀時走出去吃午飯。 總共20分鍾是迄今為止我所取得的最快成績。 今天的一位高級球員吹噓自己的節目在4秒內完成。 他在C ++工作,我知道C ++比Java快,但這很荒謬。 有人可以告訴我這里我做錯了什么。 我不能責怪語言或機器,所以一定是我。 但是,從我所看到的,Java教程使用完全相同的類,即DataInputStream 我也看過FileChannels被推薦了幾次。 他們是唯一的出路嗎?

您應該使用緩沖輸入,例如:

new DataInputStream(
    new BufferedInputStream(
        new FileInputStream(new File(input_file))))

想要文件的對象:

new ObjectInputStream(
    new BufferedInputStream(
        new FileInputStream(new File(file_name))))

更多關於差異

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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