Question

So I've written a series of Integer values between 0 and 100000 into a text file using a byte stream, to ensure that they have been stored in the correct format I'm trying to use Input Stream to view the numbers. I've tried several ways, however each time the numbers that I print out are incorrect, can anyone see where I'm going wrong, or have any ideas about alternative methods of reading the input stream:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Random;


public class Question1ByteStream {
    public static void main(String[] args) throws IOException {
        //************************************************************
        //WRITING TO THE FILE

        FileOutputStream out = null;
        try {
            out = new FileOutputStream("ByteOutStream.txt");
            for(int i = 0; i < 10000; i ++){
                Integer randomNumber = randInt(0, 100000);
                byte[] bytes = ByteBuffer.allocate(4).putInt(randomNumber).array();
                out.write(bytes);
            }
        }finally{
            if (out != null) {
                out.close();
            }
        }
        //***********************************************************
        //READING BACK FROM THE FILE

        FileInputStream in = null;

        try {
            in = new FileInputStream("ByteOutStream.txt");
            int c;

            while ((c = in.read()) != -1) {
                out.write(c);
            }
        } finally {
            if (in != null) {
                in.close();
            } 
        }

    }

    //***************************************************************
    public static int randInt(int min, int max) {
        Random rand = new Random();
        int randomNum = rand.nextInt((max - min) + 1) + min;

        return randomNum;
    }
}
Was it helpful?

Solution

Use DataInputStream.readInt().

You can write the integers much more simply with DataOutputStream.writeInt(). Use buffered streams between the data stream and the file stream when both reading and writing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top