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