When I run the following code:
int i = 0
try {
fstream = new FileWriter(filename);
BufferedWriter out = new BufferedWriter(fstream);
while (i < 100) {
out.write("My Name is Bobby Bob");
out.writ开发者_JAVA技巧e(i);
out.newLine();
i++;
}
out.flush();
out.close();
} catch (IOException e) {
e.getClass();
}
I get the following in my output file:
My Name is Bobby Bob
x100
each one is followed by a weird symbol. Male sign, female sign etc etc.
My question is and its more of a curious one. What causes these weird symbols to appear? I was expecting numbers as it counted up. Where are these symbols pulled from?
out is a RandomAccessFile ?
I think you are using write(byte) instead of write(String), so you are writting the byte X, see ASCII TABLES for representations.
Try
write(""+i);
Looking at BufferedWriter java api:
http://download.oracle.com/javase/1.4.2/docs/api/java/io/BufferedWriter.html#write(int)
it says that it writes the integer representation of a char, for your understanding.
If you want to print the value 0 you have to write 48 as this image represents:
When you write
out.write(i);
it writes the (char) i
not the number in i as text.
If you want to write i
as a number use print
out.print(i);
or
out.write(String.valueOf(i));
or
out.write(""+i);
It looks like you are writing single characters that are specified by the given int value, and not a character representation of the variable i.
System.out
is a PrintStream
. The PrintStream.write(int)
method writes a single byte to the output stream with the byte value specified. So you're not writing the integers 0 through 100, you're writing the bytes 0 through 100. You probably want print(int)
instead of write(int)
.
精彩评论