有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么输入与“1”相比?

当我浏览示例代码时,我正在刷新自己的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呢


共 (2) 个答案

  1. # 1 楼答案

    FileInputStream.read()的文档中:

    public int read() throws IOException

    因此read()返回整数,而不是字节,因此可以将其分配给int变量。 请注意,整数可以隐式转换为整数,而不会丢失。也可以从文档中看到:

    Returns: the next byte of data, or -1 if the end of the file is reached.

    针对-1的循环检查确定是否已到达文件结尾,如果已到达,则停止循环

  2. # 2 楼答案

    当到达输入端时,这个(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.