Scanner console = new Scanner(System.in);
String line = "";
String pera = " ";
System.out.println("Enter the text : ");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader buf = new BufferedReader(isr);
int lineNum = 0;
do {
line = buf.readLine();
System.out.println();
pera = line + "";
lineNum++;
System.out.print(lineNum + " " + pera);
} while (line != null);
isr.close();
buf.close();
input : Hello world I am a file Read me until end-of-file.
output : 1 Hello world 2 I am a file 3 Read me until end-of-file.
and this code output is : 1 Hello world 2 I am a file 3 Read me until end-of-file. 4 null
Let's simplify things. You can assign a variable in a while loop. Read lines one by one in it until it comes to end. We understand this when the BufferedReader
reads a null line using (line = br.readLine()) != null
.
System.out.println("Enter the text: ");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int lineNo = 0;
String line;
while ((line = br.readLine()) != null) {
System.out.println(++lineNo + " " + line);
}
isr.close();
br.close();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.