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.
for (int i = fis.read(), i >= 0, i = fis.read()) { System.out.print((char) i ); }
is more readableInputStreamReader
if you want to read chars; 2) the read on the variable declaration and immediately following print shouldn't be there: if the file is empty, the read will yield -1.=
has lower precedence than comparison operator!=
or==
so if we have code likea = b == c
it would be interpreted as if it was written likea = (b == c)
but in case of your example you first want to assign value fromfis.read()
toi
and then compare it against-1
.if ((i = fis.read()) != -1)
butwhile ((i = fis.read()) != -1)
.