Files

The program below reads a file of names and displays them.

It reads the entire line, so if there is more information on each line, it reads all of the line as name. It displays the exact contents of the file.

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
package somePackage;
import java.util.*;
import java.io.File;
import java.io.IOException;
public class someClass{
  
  public static void main(String[] args) throws IOException {
    try {
    Scanner fileName = new Scanner(new File("C:/myData/names.txt"));
    int count=0;
    while(fileName.hasNext()) {
        String name=fileName.next();
        System.out.println(name);
        count++;
    }//while: read rest of file
    if(count>0) {
        System.out.println(count+" names read");
    }
    else System.out.println("No values found");
    fileName.close();  
    } //try
    catch (IOException e) {
        System.out.println("File not found");
    }
  }//main
}//class
CODE

NEXT: