简体   繁体   English

如何使用Java计算此文件中的整数数?

[英]How do I count the number of integers in this file using Java?

If I have a given .dat file which I'm trying to read, how can I count the number of 32-bit integers? 如果我有一个要读取的给定的.dat文件,该如何计算32位整数的数量? I'm getting 2 different answers using 2 different methods. 我使用2种不同的方法得到2种不同的答案。

First method: 第一种方法:

int size = 0;
try (DataInputStream Input = new DataInputStream(
        new BufferedInputStream(new FileInputStream(file.getFD())))){
    while (true) {
        file.skipBytes(4);
        size += 1;
    }
}catch(Exception ex){
    System.out.println(ex);
}
System.out.println(size);

Second method: 第二种方法:

File fileRead = new File(file);
ret = fileRead.length() / 4

The first method is probably the most accurate since I'm reading 4 bytes each time and skipping it, to get the size of integers being packed sequentially in the file. 第一种方法可能是最准确的,因为我每次读取4个字节并跳过它,以获取按顺序打包在文件中的整数的大小。 However, the second method just gives me the direct file size and divided by 4, which is not the same. 但是,第二种方法只是给我直接文件大小,然后除以4,这是不一样的。 I think it might be including extra file related data not related to the content. 我认为这可能包括与内容无关的额外文件相关数据。

The first method is good but it is very inefficient for large files. 第一种方法不错,但是对于大文件来说效率很低。 Any idea how I can speed things up and get the number of integers efficiently? 知道如何加快速度并有效地获取整数数吗?

If you want to know hoy many times can you read a 32-bit integer from a certain binary file, Method 2 is the certain answer. 如果您想多次了解hoy,是否可以从某个二进制文件中读取32位整数,则方法2是肯定的答案。

You must not read your file through a DataInputStream unless you are certain that it was written through a DataOutputStream , because then it is not just a plain, binary file: Instead, it becomes a Java Object file , which will contain a lot of overhead data with every object written. 除非确定文件是通过DataOutputStream编写的,否则不要通过DataInputStream读取文件,因为那样的话,它不仅仅是一个普通的二进制文件:而是成为一个Java Object文件 ,其中将包含大量开销数据每个对象都写好了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM