Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File reader not reading correct values

Tags:

java

file-io

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?

like image 948
EscalatedQuickly Avatar asked Jul 03 '26 12:07

EscalatedQuickly


2 Answers

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)

like image 92
ControlAltDel Avatar answered Jul 06 '26 00:07

ControlAltDel


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

like image 33
hmjd Avatar answered Jul 06 '26 00:07

hmjd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!