Files

The program below reads a file of names and ages , parses to separate the name and year born, and displays them.

\
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
package somePackage;
import java.util.*;
import java.io.File;
import java.io.IOException;
public class SomeClass {
  
  public static void main(String[] args) throws IOException {
	int year = Calendar.getInstance().get(Calendar.YEAR);
	System.out.println("This year is "+year);
	try {
	   Scanner fileName = new Scanner(new File("C:/myData/names.txt"));
	   int count=0;
	   while(fileName.hasNext()) {
		   String input=fileName.next(); //includes name,year
		   String parts[]=input.split(",");
		   String name=parts[0];
		   int yearBorn=Integer.parseInt(parts[1]);	
		   int age=year-yearBorn;
		   System.out.println(name+" is "+age); 
		   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: That's All!