1

Oracle Java 教程中给出的示例中,他们试图将字符读取为整数...。

为什么以及如何工作?

try {
        inputStream = new FileReader("xanadu.txt");
        outputStream = new FileWriter("characteroutput.txt");

      int c;
      while ((c = inputStream.read()) != -1) {
            outputStream.write(c);
        }
4

5 回答 5

4

如果您阅读 char,则没有可用于文件结尾的值。

通过使用更大的类型int,它可以拥有每个可能的字符和另一个表示文件结尾的符号。

于 2012-05-04T17:39:02.760 回答
0

Behind the scenes in java, a char is just a 16-bit unsigned value. An int is a 32-bit unsigned value.

chars are a subset of ints whose values have meaning on the ASCII tables.

Because of this relationship, it is a convenience for syntax to allow the two types to easily converted to the other.

于 2012-05-04T17:45:46.577 回答
0

好吧,如果您阅读Reader/的文档,Writer您可以看到以下说明:

Writer 类 - 写入方法

写入单个字符。要写入的字符包含在给定整数值的低 16 位中;16 个高位被忽略。

代码只是这样做:

public void write(int c) throws IOException {
    synchronized (lock) {
        if (writeBuffer == null){
            writeBuffer = new char[writeBufferSize];
        }
        writeBuffer[0] = (char) c;
        write(writeBuffer, 0, 1);
    }
}

因此,在 的情况下Writer,据我所知,这可以通过char数据类型完成。

Reader另一方面, int 它的方法read负责返回一个字符或流指示符的结尾。

文档说:

Reader 类读取方法

读取的字符,为 0 到 65535 范围内的整数,如果已到达流的末尾,则为 -1。

因此,需要比 char 更大的数据类型,在这种情况下使用 int。

它的实现如下:

public int read() throws IOException {
    char cb[] = new char[1];
    if (read(cb, 0, 1) == -1)
        return -1;
    else
        return cb[0];
}

因此,第二种情况证明了使用更大的数据类型是合理的。

他们在两个类中都使用 int 的原因可能只是一致性问题。

于 2012-05-04T17:58:23.953 回答
0

这是因为字符是整数。每个字符都有一个等效的 unicode。

于 2012-05-04T17:38:41.577 回答
0

基本上 achar是一个int. 尝试以下操作:

char c = 'c';
int i = c;

这不会导致编译错误。

于 2012-05-04T17:39:20.903 回答