31

我正在写一个OutputStream,只是在OutputStream接口中注意到了这一点,

   public abstract void write(int b) throws IOException;

此调用将一个字节写入流,但为什么它需要整数作为参数?

4

5 回答 5

26

所以你可以发出EOF信号:

“注意 read() 返回一个 int 值。如果输入是字节流,为什么 read() 不返回一个字节值?使用 int 作为返回类型允许 read() 使用 -1 来表示它已经到了溪流的尽头。”

http://java.sun.com/docs/books/tutorial/essential/io/bytestreams.html

于 2009-09-10T22:55:40.780 回答
10

Actually I've been working with bytes a bit lately and they can be annoying. They up-convert to ints at the slightest provocation and there is no designation to turn a number into a byte--for instance, 8l will give you a long value 8, but for byte you have to say (byte)8

On top of that, they will (pretty much) always be stored internally as ints unless you are using an array (and maybe even then.. not sure).

I think they just pretty much assume that the only reason to use a byte is i/o where you actually need 8 bits, but internally they expect you to always use ints.

By the way, a byte can perform worse since it always has to be masked...

At least I remember reading that years ago, could have changed by now.

As an example answer for your specific question, if a function (f) took a byte, and you had two bytes (b1 and b2), then:

f(b1 & b2)

wouldn't work, because b1 & b2 would be up-converted to an int, and the int couldn't be down-converted automatically (loss of precision). So you would have to code:

f( (byte)(b1 & b2) )

Which would get irritating.

And don't bother asking WHY b1 & b2 up-converts--I've been cussing at that a bit lately myself!

于 2009-09-11T00:52:42.820 回答
7

根据OutputStream的 javadoc ,此函数将忽略 24 个高位。我认为该方法的存在是出于兼容性原因:因此您不需要先转换为字节,您可以简单地传递一个整数。

问候

于 2009-09-10T21:42:42.577 回答
3

Java IOStream 类自 1.0 以来一直是 Java 的一部分。这些类只处理 8 位数据。我的猜测是,接口是这样设计的,以便为 int、short、byte 和 char 值调用一个 write(int b) 方法。这些都被提升为int。事实上,由于大多数 JVM 运行在 32 位机器上,因此 int 原语是最有效的处理类型。无论如何,编译器都可以自由地使用 32 位存储诸如字节之类的类型。有趣的是, byte[] 确实存储为 8 位字节序列。这是有道理的,因为数组可能非常大。但是,对于单个原始值(例如 int 或 byte),只要行为符合规范,运行时占用的最终空间并不重要。

更多背景:

http://www.java-samples.com/showtutorial.php?tutorialid=260

The assumption for the IOStream classes is that the caller only really cares about lowest 8 bits of data even when passing in an int. This is fine as long the caller knows it is really dealing with bytes, but it becomes a problem when underlying data is really text that uses some other character encoding such as multi-byte Unicode. This is why the Reader classes were introduced way back with Java 1.1. If you care about text data and performance, the IOStream classes are faster, but the Reader classes are more portable.

于 2009-09-10T23:01:32.823 回答
2

Maybe it's because bytes are signed by default, and files store bytes as unsigned values. That is why read() returns an int - to give 255 instead of -1 for $FF. Same with write(int), you can not store $FF as 255 in a byte.

于 2009-09-11T07:14:43.263 回答