Reputation: 19
i'm currently writting an algorithm who write another algorithm. For this i'm using the FileWritter class and this worked fine until i tried to write integers in the file.
fileWriter.write(1);
print `` (edit : you can't see the character in here) that intelliJ interpret as : Illegal Character U+0001
(every number has a different name of illegal character)
When i'm doing fileWriter.write("1")
this work fine.
Does the problem come from Intellij or do i have to convert every integers to String ?
Upvotes: 1
Views: 149
Reputation: 180
The FileWriter.write(int)
method, which is inherited from OutputStreamWriter.write(int)
, writes a single character to a file. The input int
is the ASCII or Unicode representation of the character. For instance, writing fileWriter.write(65)
writes the letter A
, as A
's ASCII value is 65. This could also be written as fileWriter.write('A')
, as the character A
is represented in memory as the number 65
. If you want to write an integer to a file, you will need to call fileWriter.write(Integer.toString(i))
, where i
is the value you want to write. Alternatively, if i
is a single-digit positive number, you can write fileWriter.write('0' + i)
, as adding '0'
to such a digit converts it into its corresponding character.
Upvotes: 0
Reputation: 1502806
Basically Writer.write(int)
doesn't do what you expect it to. The documentation says:
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.
So you're writing U+0001, just as IntelliJ is saying.
It's not the greatest API in the world (it would be better to accept char
for a single character) but it is behaving as designed.
Basically, yes, you need to convert everything to text.
Upvotes: 5