这个程序中的 `if ((i = fis.read()) != -1)` 这一行代码是什么意思?

huangapple go评论63阅读模式
英文:

what exactly if ((i = fis.read()) != -1) means in this program?

问题

package IO;
import java.io.*;
public class test {

    public static void main(String[] args) throws IOException {
        File f1 = new File("C:\\Users\\rs\\New folder\\myname.txt");
        try {
            FileInputStream fis = new FileInputStream(f1);
            int i = fis.read();        
            System.out.print((char)i);
            while((i = fis.read()) != -1) {
                System.out.print((char) i );
            }
            
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

我是一个新的Java程序员,我在这段代码中遇到了一些问题。这段代码从文件f1中读取字节,然后我可以将这些字节转换为字符并打印出来,但有一些东西我不太明白,那就是我的while循环中的条件。它到底是什么意思?我的意思是,if ((i = fis.read()) != -1) 到底意味着什么?第二个问题是,为什么我们将 i = fis.read() 放在括号中?我的文件中有一行文本。

英文:
package IO;
import java.io.*;
public class test {

public static void main(String[] args) throws IOException {
	File f1 = new File("C:\\Users\\rs\\New folder\\myname.txt");
	try {
		FileInputStream fis = new FileInputStream(f1);
		int i = fis.read();		
		System.out.print((char)i);
		while((i = fis.read())!= -1) {
			System.out.print((char) i );
		}
		
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	

 }

}

I am a new java programmer and i have a trouble in this code. This code reads bytes from my file (f1) and I can cast this bytes to char and print them, but something is here that I do not understand and its the condition in my while loop. What it exactly means? I mean what exactly if ((i = fis.read()) != -1) means??? And the second question is why we put
i = fis.read() in a paranthesis???
My file has a text (1 line) in it.

答案1

得分: 5

FileInputStreamread() 方法遵循以下逻辑:

从此输入流中读取一个字节的数据。
如果尚无输入可用,此方法将阻塞。

该方法将返回

下一个数据字节,如果已到达文件的结尾,则返回 -1。

因此,-1 是用于检查 EOF 的标志。有了这个理解,此代码段

while((i = fis.read())!= -1) 
      System.out.print((char) i);

表明:

1. 将 fis.read() 赋值给变量 i

2a. 如果 i != -1,则打印表示刚刚从输入流中读取的整数的 ASCII 字符,并继续循环

2b. 如果 i == -1,则结束循环 / 停止读取,因为已达到文件的结尾。

英文:

FileInputStream 's read() method follows this logic:

> Reads a byte of data from this input stream.
This method blocks if no input is yet available.

The method will return:

> The next byte of data, or -1 if the end of the file is reached.

So -1 is its flag for the EOF check. With this in mind, this code snippet

while((i = fis.read())!= -1) 
      System.out.print((char) i);

Is telling that:

1. Assign fis.read() to the var i

2a. If i != -1, print the ASCII char representing the integer just read from the inputstream, and continue the loop.

2b. If i == -1, end the loop / stop reading, because it reached the end of file.

答案2

得分: 4

第一个问题

这意味着你会继续从流中读取,直到达到末尾。当 fis.read() 返回 -1 时,意味着你已经到达流的末尾,没有更多的数据可供读取。

第二个问题

i = fis.read() != -1

你可能会产生这样的印象,即编译器不知道正确的执行顺序,有两种情况:

  • 我们检查 fis.read() != -1boolean 结果),然后将其赋值给 i
  • 我们获取 fis.read() 并将其赋值给 i,然后检查 i != -1

但是 Java 有明确定义的规则,只有一种情况是因为运算符优先级。

请参阅文档:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

赋值的优先级低于 !=,因此肯定会发生第一种情况。
但这不是我们想要的。(我们不希望 ifis.read() != -1 的布尔结果)

另请参阅:
https://introcs.cs.princeton.edu/java/11precedence/#:~:text=Java%20has%20well-defined%20rules,be%20overridden%20by%20explicit%20parentheses.

“通过显式括号可以覆盖优先级规则”

因此,我们明确地添加了括号,以确保其中的语句(i = fis.read())首先被执行,从而发生第二种情况。

英文:

First Question

That means you would continue reading from the stream until you reached the end. When fis.read() returns -1, that means that you reached the end of the stream and there is no more data to read.

Second Question

i = fis.read() != -1

You might get the impression that the compiler does not know the proper order of execution and there are two scenarios:

  • We check fis.read() != -1 (boolean result) then assign it to i
  • We get fis.read() and assign it to i then check i != -1

But java has well-defined rules, there is only one because of operator precedence.

See the table at:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

Assignment has a lower precedence than !=, so definitely the first scenario will happen.
But that is not what we want. (We don't want i to be the boolean result of fis.read() != -1)

Also see:
https://introcs.cs.princeton.edu/java/11precedence/#:~:text=Java%20has%20well-defined%20rules,be%20overridden%20by%20explicit%20parentheses.

"Precedence rules can be overridden by explicit parentheses"

So we explicitly put the parentheses to make sure the statement inside it (i = fis.read()) is executed first and the second scenario happens.

答案3

得分: 2

这意味着

> “读取直到找到文件结束字符为止”。

至于第二个问题:

while((i = fis.read())!= -1) {
    System.out.print((char) i );
}

(i = fis.read()) 定义了在循环中用于打印的 “i 变量”,同时检查它是否不等于 -1

英文:

It means

> "read until the find the end of file char".

And for the second question:

while((i = fis.read())!= -1) {
    System.out.print((char) i );
}

The (i = fis.read()) defines that "i variable" for the print below while check if it's different from -1.

答案4

得分: 2

你可以将(i = fis.read())!= -1看作是在执行两个单独的操作。

首先会执行i = fis.read(),也就是从输入流中读取一个字节。如果没有可读内容,那么i会被设置为-1。

其次会进行这个比较:i != -1。如果为真,则循环继续。如果为假,则循环结束。

英文:

You can think of (i = fis.read())!= -1 as doing two separate things.

First i = fis.read() is executed. That is, you read a byte from the input stream. If there is nothing to read then i is set to -1.

Second this comparison happens: i != -1 If that is true the loop continues. If that is false the loop ends.

huangapple
  • 本文由 发表于 2020年7月26日 00:54:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63091009.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定