Java Reference
In-Depth Information
Display 10.3 Reading Input from a Text File Using Scanner (part 1 of 2)
1
import java.util.Scanner;
2
import java.io.FileInputStream;
3
import java.io.FileNotFoundException;
4
5 public class TextFileScannerDemo
6{
7
public static void main(String[] args)
8
{
9
System.out.println("I will read three numbers and a line");
10
System.out.println("of text from the file morestuff.txt.");
11
12
Scanner inputStream = null ;
13
14
try
15
{
16
inputStream =
17
new Scanner( new FileInputStream("morestuff.txt"));
18
}
19
catch (FileNotFoundException e)
20
{
21
System.out.println("File morestuff.txt was not found");
22
System.out.println("or could not be opened.");
23
System.exit(0);
24
}
25
int n1 = inputStream.nextInt( );
26
int n2 = inputStream.nextInt( );
27
int n3 = inputStream.nextInt( );
28
29
inputStream.nextLine(); //To go to the next line
30
31
String line = inputStream.nextLine( );
32
33
System.out.println("The three numbers read from the file are:");
34
System.out.println(n1 + ", " + n2 + ", and " + n3);
35
36
System.out.println("The line read from the file is:");
37
System.out.println(line);
38
39
inputStream.close( );
40
}
41
}
F ILE morestuff.txt
This file could have been made with a
text editor or by another Java
program.
1 2
3 4
Eat my shorts.
 
Search WWH ::




Custom Search