0

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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Programming is mostly playing with binary, and you have all the time in the world. So try something, and ask about details that are unclear to you. – ruslik Dec 03 '10 at 01:29
  • Hint: what method do you think would be used to read things that were written with a method called "writeInt"? – Laurence Gonsalves Dec 03 '10 at 01:43

1 Answers1

0

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.

Xiangdong
  • 254
  • 2
  • 10
  • Of course, using exceptions for control flow isn't terribly good style. If only there was some way to figure out how many ints are in that file. – Dmitri Dec 03 '10 at 02:47
  • @Dmitri: If writeInt writes a constant number of bytes for every argument, you could divide the file length by that number to get the number of integers in the file. – Thomas Dec 03 '10 at 18:18
  • @Thomas: I was using gentle sarcasm to guide the author of the question towards the path to a solution :) – Dmitri Dec 03 '10 at 23:13