import java.io.*; import java.util.Scanner; import javax.swing.JFileChooser; public class ReadAFile { /** * @param args */ public static void main(String[] args) throws IOException{ ///create a file dialog //open with current directory JFileChooser chooser = new JFileChooser("."); int returnVal = chooser.showOpenDialog(null); if(returnVal == JFileChooser.APPROVE_OPTION){ //the user hit "ok" //get the selected file File file = chooser.getSelectedFile(); String absName = file.getAbsolutePath(); String name = file.getName(); System.out.println("Absolute Path: " + absName); System.out.println("Name: " + name); Scanner fileInput = new Scanner(file); //Reads one "word" at a time //while(fileInput.hasNext()){ // System.out.println(fileInput.next()); //} //read a data format //number of lines //each line has a name and two grades int numRecords = fileInput.nextInt(); //for(int i = 0; i < numRecords; i++){ //read a name //String studentName = fileInput.next(); //read grade1 //int grade1 = fileInput.nextInt(); //read grade2 //int grade2 = fileInput.nextInt(); //System.out.printf("%s: %d, %d\n", studentName, grade1, grade2); //} //different format (comma delimited) fileInput.nextLine(); //throw away first newline character for(int i = 0; i < numRecords; i++){ String line = fileInput.nextLine(); String[] words = line.split(","); String studentName = words[0]; int grade1 = Integer.parseInt(words[1]); int grade2 = Integer.parseInt(words[2]); System.out.printf("%s: %d, %d\n", studentName, grade1, grade2); } } } }