FileInputStream/DataInputStream

4.5k Views Asked by At

So, we got an assignment to make a guessing game. The program has to generate a number and the user has to guess. After the users guesses right, the program shows the "Highscore" (how many times the user had to guess before he got it right).

Then we should save this highscore in a text-file, so that it is saved on the computer, and if you restart the computer it will not be lost. What I am struggeling with is how the program is supposed to read the file I saved.

This is my "write-code":

try {
    FileOutputStream write = new FileOutputStream 
    DataOutputStream out = new DataOutputStream(write);
    out.writeBytes(""+highscore);
    write.close();}
catch(IOException ioException ){
    System.err.println( "Could not write file" );
    return;}

Which works fine, but I don't know how to read it again. My "read-code": (I just guessed, I don't know if this would work)

try{
    FileInputStream read = new FileInputStream
    DataInputStream in = new DataInputStream(read);
    in.readBytes(""+highscore);
    JOptionPane.showMessageDialog(null, "Your highscore is" + highscore);
catch(IOException ioException ){
    System.err.println( "Could not read file" );
    return;}

Now, I dont know if the in.readBytes(""+highscore); command is correct. I just guessed (I thought if out.writeBytes(""+highscore); worked then surely read has to work too)

If readBytes is the correct command then I get this error :

The method readBytes(String) is undefined for the type DataInputStream

What am I supposed to do?

Some information: The highscore is and int.

1

There are 1 best solutions below

0
On

For example, if highscore is an int, you'll want to write an int to the file. You can do that with

DataOutputStream out = new DataOutputStream(write);
out.writeInt(highscore);

and read it with

DataInputStream in = new DataInputStream(read);
int highscore = in.readInt();

The class DataInputStream does not have a readBytes(). That is why your program does not compile.

The whole point of DataIOStream classes is to read and write

primitive Java data types from an underlying [...] stream in a machine-independent way.

So use the methods corresponding to the data type of highscore.