Reading a .dat file into an array in Java

Ben picture Ben · Apr 17, 2014 · Viewed 30.3k times · Source

The code that I'm writing has two classes: writeInts and readInts. I wrote writeInts to randomly generate 100 numbers between 0 and 1000 and output them to a data.dat file.

readInts is supposed to open a DataInputStream object and read in the "raw" data from the data.dat file and store the 100 integers in an array. My problem is that I can't seem to read the data correctly. Any help with this would be greatly appreciated. Thanks!

writeInts:

import java.io.*;


public class WriteInts {
    public static void main(String[] args) throws IOException {
        DataOutputStream output = new DataOutputStream(new FileOutputStream("data.dat"));
        int num = 0 + (int)(Math.random());
        int[] counts = new int[100];
        for(int i=0; i<100; i++) {
            output.writeInt(num);
            counts[i] += num;

            System.out.println(num);
        }
        output.close();
    }

}

readInts:

import java.io.*;
import java.util.*;

public class ReadInts {
    public static void main(String[] args) throws IOException {

        // call the file to read
        Scanner scanner = new Scanner(new File("data.dat"));
        int[] data = new int[100];
        int i = 0;
        while (scanner.hasNextInt()) {
            data[i++] = scanner.nextInt();

            System.out.println(data[i]);

            scanner.close();
        }

    }

}

Answer

Denis Kulagin picture Denis Kulagin · Apr 17, 2014

If you want to write binary data, use DataInputStream/DataOutputStream. Scanner is for text data and you can't mix it.

WriteInts:

import java.io.*;

public class WriteInts {
    public static void main(String[] args) throws IOException {
        DataOutputStream output = new DataOutputStream(new FileOutputStream(
                "data.dat"));

        for (int i = 0; i < 100; i++) {
            output.writeInt(i);
            System.out.println(i);
        }

        output.close();
    }

}

ReadInts:

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class ReadInts {
    public static void main(String[] args) throws IOException {
        DataInputStream input = new DataInputStream(new FileInputStream(
                "data.dat"));

        while (input.available() > 0) {
            int x = input.readInt();
            System.out.println(x);
        }

        input.close();
    }

}