EscalatedQuickly
EscalatedQuickly

Reputation: 402

File reader not reading correct values

I'm pretty new to Java, and I've written two small functions to read and write data to a file. The data being written is the x and y coordinates of a character on the map in a game. The data written to the file seems to be all right:

234
-123

I write the data with the following code:

public void save(int x, int y)
{
    try
    {
        FileWriter fstream = new FileWriter("skygrim.txt");  //Create save-file
        BufferedWriter out = new BufferedWriter(fstream);    //New writer, connected to save-file
        out.write(x + "\n" +y);        //Write position to file 
        out.close();                   //Close file
    }catch (Exception e){System.out.println("Error: " + e.getMessage());}
}

When I later want to read the data, to be able to "load" a saved game, I get the following values from the file:

50
51

I use the following code to read from the file:

public int[] read(String file)
{
    int[] coordinates = new int[2];
    try
    {
        FileReader fstream = new FileReader(file);
        BufferedReader in = new BufferedReader(fstream);
        coordinates[0] = in.read();
        coordinates[1] = in.read();
        in.close();
    }catch(Exception e){System.out.println("Error" + e.getMessage());}
    System.out.println("x: " + coordinates[0]);
    System.out.println("y: " + coordinates[1]);
    return coordinates;
}

Why does the program read the file so terribly wrong, and what can I do about it?

Upvotes: 2

Views: 1232

Answers (4)

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78579

Use the readLine() method of your BufferedReader object to avoid reading a single character as read() method does.

coordinate[0] = Integer.parseInt(reader.readLine());
coordinate[1] = Integer.parseInt(reader.readLine());

Upvotes: 0

hmjd
hmjd

Reputation: 121971

BufferedReader.read() reads a single character, not an int. A possibility would be to use java.util.Scanner and its method nextInt().

Upvotes: 2

ControlAltDel
ControlAltDel

Reputation: 35011

your read method is reading the first two characters of the file: '2' and '3'. You probably want to use BufferedReader.readLine()

Also see Integer.parseInt(String)

Upvotes: 9

Wei Ma
Wei Ma

Reputation: 3155

 coordinates[0] = in.read();
 coordinates[1] = in.read();

Only read one byte with each call. In this case you are getting '2' and '3' (50 and 51 are their ascii code). And hence the wrong value.

Upvotes: 0

Related Questions