KaiquanMah commited on
Commit
2089b65
·
verified ·
1 Parent(s): cd0c274

Create 16a Files and exceptions

Browse files
Week 3: Objects, files and exceptions/16a Files and exceptions ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Read from a file in Java
2
+ - can use Scanner class - BUT read from file
3
+ - and endpoint is known (for a file)
4
+ vs
5
+ - cuz Scanner usu reads from keyboard - System.in stream
6
+
7
+
8
+
9
+
10
+
11
+ eg
12
+ names.txt
13
+ Jack
14
+ Jane
15
+ Pia
16
+ Pete
17
+ Andrew
18
+ Ann
19
+ Lisa
20
+ Larry
21
+
22
+
23
+
24
+ // read contents of the file - names.txt
25
+ import java.io.File;
26
+ import java.util.Scanner;
27
+
28
+ public class Example {
29
+ public static void main(String[] args){
30
+
31
+ // create File object, read from filepath
32
+ File file = new File("names.txt");
33
+
34
+ // direct the scanner to a file
35
+ try(Scanner reader = new Scanner(file)) {
36
+
37
+ while (reader.hasNextLine()) {
38
+ System.out.println(reader.nextLine());
39
+ }
40
+
41
+ }
42
+ catch (Exception e) {
43
+ System.out.println("An error happened!");
44
+ }
45
+ }
46
+ }
47
+
48
+ Program outputs:
49
+ Jack
50
+ Jane
51
+ Pia
52
+ Pete
53
+ Andrew
54
+ Ann
55
+ Lisa
56
+ Larry
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+