【问题标题】:hash symbol is displayed in file in java哈希符号显示在java中的文件中
【发布时间】:2018-11-02 14:52:34
【问题描述】:
 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();

我不明白为什么会这样。

【问题讨论】:

  • fo.write(2) 实际上并不是写数字 2,而是写一个字节。见docs.oracle.com/javase/9/docs/api/java/io/…
  • 标签只是一种社交媒体功能。在这种情况下,说你可以看到一个主题标签是没有意义的。这就像说“我可以看到一条推文”。你在看什么?哈希符号 (#)?还是别的什么?
  • 是一个井号
  • 如果你想将人类可读的文本写入文件,你应该使用Writer,而不是OutputStream
  • 我想这里的大多数人都会知道,当人们写“hashtag”时,它甚至是井号和井号的同义词。虽然我同意这不是符号的正确名称,但它仍然有意义并且可以推断其含义。

标签: java file fileoutputstream


【解决方案1】:

你必须写字符串。您可以尝试以下方法之一:

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

这是因为 fo.write(int) 方法实际上并没有写入 int 本身,它以指定的编码(如果未指定,则为 utf-8)写入 int 表示的字符。

【讨论】:

    【解决方案2】:

    你要明白的是

    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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2015-11-02
      • 2019-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多