为什么writeInt(int v)在文件中显示为符号,但writeBytes(String s)在文件中正确显示?

时间:2015-06-26 09:15:43

标签: java

我试图理解为什么当我使用这段代码时(使用writeInt(int v))我在创建的文件中得到符号。

public class Write {
    public static void main(String[] args) {
        try {
          //create FileOutputStream object
          FileOutputStream fos = new FileOutputStream("v.txt");
          DataOutputStream dos = new DataOutputStream(fos);
          int str = 2323;
          dos.writeInt(str);
          dos.close();
        } catch (IOException e) {
            System.out.println("IOException : " + e);
        }
    }
}

但是当我使用writeBytes(String s)writeUTF(String s)时,我会在文件中找到正确的字符串。我已经读过writeBytes将原始数据byte转换为字节序列,那么为什么我不能使用这种方法得到我使用前面代码得到的符号呢?

public class Write {
    public static void main(String[] args) {
        try {
          //create FileOutputStream object
          FileOutputStream fos = new FileOutputStream("v.txt");
          DataOutputStream dos = new DataOutputStream(fos);
          String str = "hello";
          dos.writeBytes(str);
          dos.close();
        } catch (IOException e) {
            System.out.println("IOException : " + e);
        }
    }
}

另外我已经读过writeBytes忽略了每个字符的8个高位,但是我没有看到我输入的字符串和文件中的任何区别,所以任何人都可以解释它是什么意思忽略了8位?

1 个答案:

答案 0 :(得分:2)

The result is as expected. The number 1094861636 happens to be 41424344 in hexadecimal and the ascii codes for A, B, C and D happens to be 41, 42, 43, 44 in hexadecimal.

What writeInt does is to break down the number into binary format and output the bytes (8 binary "digits" chunks). Hexadecimal is nifty because each hexadecimal "digit" happens to correspond to four binary "digits".

What you probably want to do is use writeStr(Integer.toString(yourNumber)) instead. Integer.toString converts an integer to its human readable form, while writeInt produces something that is more computer readable.