I am writing to a file for the first time, but the text on the file comes out completely wrong. Instead of numbers (which it is supposed to print), it prints unrecognizable characters. I can't seem to understand why this is happening? (in my code the print statement is inside a for loop, but this is the "shell" around the loop)
Is there a logical explanation for this?
try {
FileWriter outFile = new FileWriter("newFile.txt", true);
outFile.write(number);
} catch (IOException e) {
e.printStackTrace();
}
You're calling Writer.write(int)
:
Writes a single character. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored.
My guess is that's not what you want to do. If you want to write the text representation of a number, you need to do that explicitly:
outFile.write(String.valueOf(number));
(Personally I'd recommend using OutputStreamWriter
wrapped around a FIleOutputStream
, as then you can - and should - specify an encoding. FileWriter
always uses the platform default encoding.)
See more on this question at Stackoverflow