Java FileWriter outputs a question mark

I have been unable to find the reason for this. The only problem I am having in this code is that when the FileWriter tries to put the new value into the text file, it instead puts a ?. I have no clue why, or even what it means. Here is the code:

if (secMessage[1].equalsIgnoreCase("add")) {
    if (secMessage.length==2) {
        try {
            String deaths = readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset());
            FileWriter write = new FileWriter("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt");
            int comb = Integer.parseInt(deaths) + 1;
            write.write(comb);
            write.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

And here is the readFile method:

static String readFile(String path, Charset encoding) throws IOException {
    byte[] encoded = Files.readAllBytes(Paths.get(path));
    return new String(encoded, encoding);
}

Also, the secMessage array is an array of strings containing the words of an IRC message split into individual words, that way the program can react to the commands on a word-by-word basis.

Jon Skeet
people
quotationmark

You're calling Writer.write(int). That writes a single UTF-16 code point to the file, taking just the bottom 16 bits. If your platform default encoding isn't able to represent the code point you're trying to write, it will write '?' as a replacement character.

I suspect you actually want to write out a text representation of the number, in which case you should use:

write.write(String.valueOf(comb));

In other words, turn the value into a string and then write it out. So if comb is 123, you'll get three characters ('1', '2', '3') written to the file.

Personally I'd avoid FileWriter though - I prefer using OutputStreamWriter wrapping FileOutputStream so you can control the encoding. Or in Java 7, you can use Files.newBufferedWriter to do it more simply.

people

See more on this question at Stackoverflow