简体   繁体   中英

Binary I/O Classes (Summing all the integers in a binary data file)

Could someone please help me through this problem? I'm not really good with the binary I/O classes.

Suppose a binary data file named Exercise 13b_1.dat has been created using writeInt(int) in DataOutputStream. The file contains an unspecified number of integers. Write a program to find the sum of integers.

Here is a simple solution.

FileInputStream fis = new FileInputStream("13b_1.dat");
DataInputStream dis = new DataInputStream(fis);
int count = 0;

try {
    while (true) {
        dis.readInt();
        count++;
    }

} catch (EOFException e) {}

System.out.println("There are " + count + " integers.");

For efficiency, you can read in a bunch of bytes and divide the number of bytes by four, since one integer is four bytes.

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