gpt4 book ai didi

java - 为什么 write() 和 read() 似乎写入和读取超过一个字节?

转载 作者:行者123 更新时间:2023-11-29 04:07:43 25 4
gpt4 key购买 nike

Java中,一个byte可以容纳的最大值是127,也就是8位。此外,FileInputStream 使用的 read() 方法(它继承自 InputStream)声明它只读取一个 byte,而 write( ) FileOutputStream 使用的方法(它继承自 OutputStream)声明它只写入一个 byte。但是,当我将大于 127 但小于 256 的数字传递给 write() 然后 read() 它时,我得到一个十进制值确实在 127 和 255 之间的字符。这似乎表明 write() 可以实际上写 9 位而不是 8 位,而 read() 实际上可以读取 9 位而不是 8 位。所以,我的问题是这怎么可能? read() 如何读取超过 byte 的内容以及 write() 如何写入超过 byte 的内容?还有什么我想念的吗?

再举一个例子,假设我将整数 1000 传递给 write()。 write() 然后输出一个字符,read() 然后读取为具有 232 的十进制值。这似乎是因为 1000 - 512 - 256 = 232,这似乎再次表明 write() 和 read() 写和读取 9 位(最多 255)而不是一个字节(8 位,最多 127)。在我看来,write() 正在写入 1000 的低 9 位,然后 read() 读取,在本例中为 232。

我已经发布了我用来测试这一切的程序。另外,我对 Java 还很陌生,所以非常感谢任何帮助或想法!

import java.io.*;

public class TestingCharsAndBytes
{

public static void main(String[] args)
{

FileOutputStream output = null;
FileInputStream input = null;
try
{
output = new FileOutputStream(".../testFileIO1.txt");
input = new FileInputStream(".../testFileIO1.txt");

// Stuff to try:


doFileResult(512,output,input);
doFileResult(128,output,input);
doFileResult(256,output,input);
doFileResult(257,output,input);
doFileResult(160,output,input);
doFileResult(289,output,input);
doFileResult(1000,output,input);
doFileResult(2000,output,input);
}
catch(IOException e)
{
System.out.println("Error occurred.");
e.getStackTrace();
}
finally
{
try
{
output.close();
input.close();
}
catch(Exception e)
{
System.out.println("Error closing file.");
}
}
}
public static void doFileResult(int toWrite, FileOutputStream outStream, FileInputStream inputStream) throws IOException
{
System.out.println("******************");
outStream.write(toWrite);

int x = inputStream.read();
char y = (char) x;

System.out.println("Integer passed to write: " + toWrite);
System.out.println("Input integer read: " + x);
System.out.println("Input character read (after casting to char): " + y);
System.out.println();
}
}

最佳答案

Per the documentation , read() 使用-1作为特殊值来表示EOF。如果使用字节的实际范围 (-128..127),则 -1 将是一个有效字节。

如基本方法文档中所述,InputStream.read() :

The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned.

编写从流中读取的代码的惯用方式是这样的:

while (true) {
int v = stream.read();
if (v == -1) {
break;
}
byte b = (byte) v;
// Do something.
}

字节转换将“正确”将 int 0..255 映射到字节 -128..127,因为从 32 位缩小到 8 位将仅保留 8 个最低有效位。

关于java - 为什么 write() 和 read() 似乎写入和读取超过一个字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57299428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com