Java Reference
In-Depth Information
Display 10.4
Checking for the End of a Text File with
hasNextLine
(part 1 of 2)
1
import
java.util.Scanner;
2
import
java.io.FileInputStream;
3
import
java.io.FileNotFoundException;
4
import
java.io.PrintWriter;
5
import
java.io.FileOutputStream;
6
7
public class
HasNextLineDemo
8{
9
public static void
main(String[] args)
10
{
11
Scanner inputStream =
null
;
12
PrintWriter outputStream =
null
;
13
try
14
{
15
inputStream =
16
new
Scanner(
new
FileInputStream("original.txt"));
17
outputStream =
new
PrintWriter(
18
new
FileOutputStream("numbered.txt"));
19
}
20
catch
(FileNotFoundException e)
21
{
22
System.out.println("Problem opening files.");
23
System.exit(0);
24
}
25
String line =
null
;
26
int
count = 0;
27
while
(inputStream.hasNextLine( ))
28
{
29
line = inputStream.nextLine( );
30
count++;
31
outputStream.println(count + " " + line);
32
}
33
inputStream.close( );
34
outputStream.close( );
35
}
36
}
File original.txt
Little Miss Muffet
sat on a tuffet
eating her curves away.
Along came a spider
who sat down beside her
and said "Will you marry me?"