Spaces:
Running
Running
| 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 | |