gpt4 book ai didi

java - 为什么输入与 "-1"进行比较?

转载 作者:行者123 更新时间:2023-11-30 02:42:45 25 4
gpt4 key购买 nike

当我检查示例代码时,我正在刷新 I/O 知识,我看到了一些让我困惑的东西:

public class CopyBytes {
public static void main(String[] args) throws IOException {

FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;

while ((c = in.read()) != -1) {
out.write(c);
}

如何将 int 值 (c) 分配给输入流 (in.read()) 中的一个字节数据?为什么 while 循环要等待它不等于 -1?

最佳答案

当到达输入末尾时,此 (c = in.read()) 将返回 -1,因此 while 循环将停止。

阅读这篇精彩文章answer .

来自 Oracle 文档:

public abstract int read() throws IOException Reads the next byte of data from the input stream. 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. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown. A subclass must provide an implementation of this method.

Returns: the next byte of data, or -1 if the end of the stream is reached. Throws: IOException - if an I/O error occurs.

关于java - 为什么输入与 "-1"进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41155543/

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