哈希符号显示在 java 中的文件中

hash symbol is displayed in file in java

 File f = new File("even.txt");
 FileOutputStream fo = new FileOutputStream(f);
 int a = 2;
 fo.write(a);
 fo.close();

每当我 运行 这个程序并打开 "even.txt" 文件时,我只能在文件中看到一个哈希符号。当我使用字符串时不会发生这种情况。

 File f = new File("even.txt");
 FileOutputStream fo = new FileOutputStream(f);
 String s = "2";
 byte b[] = s.getBytes();
 fo.write(b);
 fo.close();

我不明白为什么会这样。

你必须写字符串。您可以尝试其中之一:

wr.write("222");
wr.write(new Integer(222).toString());
wr.write( String.valueOf(222) );

因为fo.write(int)方法实际上并没有写入int本身,而是将int所代表的字符按照指定的编码写入(不指定则为utf-8)

你要明白的是

int a = 2;
fo.write(a); //This line write the byte 0x02 to the inputstream because that is the binary representation of the digit 2

String s = "2";
byte b[] = s.getBytes();
fo.write(b); //This one write 0x32 to the inputstream because that is the ascii respresentation of the character "2" which is return by getBytes() from the string class

您可以在十六进制编辑器中检查代码生成的两个文件之间的差异