Reputation: 1
I cam across this code in my java class... but still i cannot understand how this code reads a file.. specially the while loop part...lecturer said if we do not implement loop.. this code reads only 1st letter of the file....
import java.io.FileReader;
public class NewClass {
public static void main(String[] args) {
try{
FileReader f1 = new FileReader("E:\\SOFTWARE setups\\Apache\\new.txt");
while (true) {
int x = f1.read();
if (x == -1) {
break;
}
char y = (char) x;
System.out.print(y);
}
Upvotes: 0
Views: 142
Reputation: 309
read() method reads single character, returns -1 when reaches to end of file.
While loop can be optimized and can be written like shown below
int x;
while ( (x = f1.read()) !=-1) {
System.out.print((char)x);
}
Upvotes: 0
Reputation: 309
The read() method reads a single character, it returns either integer value of character or -1. Returns -1 if the end of the file has been reached.
Upvotes: 0
Reputation: 29166
From the documentation -
Reads a single character.
Returns the character read, or -1 if the end of the stream has been reached.
So yes, you need a for loop to read the entire content of your file. The basic strategy that your code is following is to read one character at a time, check to see if it's -1 (to see if end of file has been reached) and if not, print it on the console.
If you don't want to write a loop like this and read the whole content, then you can use some utility library like Apache Commons -
File file = new File("E:\\SOFTWARE setups\\Apache\\new.txt");
String content = FileUtils.readFileToString(file);
System.out.print(content);
Upvotes: 2