简体   繁体   中英

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? I'm getting 2 different answers using 2 different methods.

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. However, the second method just gives me the direct file size and divided by 4, which is not the same. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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