Search code examples
javaeclipsefilewriterbufferedwriter

Writing a file to text with BufferedWriter(Writes something strange)Java


I try to write some integers to a text file with entering only one value to each line so I used BufferedWriter.

try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                          new FileOutputStream("filename.txt"), "utf-8"))) {
    writer.write(board.Player1.money);             
    writer.newLine();
    //Continues to do this for 4 players.
    writer.newLine();
    writer.write(board.Player1.position);
    writer.newLine();
    //Continues to do this for 4 players.
}

What I expected to see was integers in my text file. And values like board.Player1.money are correct because they are working for the other parts of the code. So I expect to see a value like 300 but I see the following lines in a text file.

Ǵ
ಀ
ಀ
ಀ

Why is that?


Solution

  • The write(...) method of the BufferedWriter is overloaded.

    For example: there is the method void write(String arg) which writes the given String to the file and there is void write(int arg) which converts the given Integer to a character and then writes the character to the file.

    To solve your propblem you'll have to change

    writer.write(board.Player1.position);
    

    to

    writer.write(Integer.toString(board.Player1.position));