Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More on Files COMP 102 #
© Peter Andreae COMP : 2 Menu More dealing with files Running a program without BlueJ: the main method Reading: L-D-C: Administration Assignment 5: Trickier code – don’t leave until the last minute
© Peter Andreae COMP : 3 Testing end of file Unlike UI text pane, can test for end of file: /** Finds oldest person in file of names and ages. */ public void printOldest(){ try { Scanner scan = new Scanner(new File(“names.txt")); String oldest = “”; int maxAge = 0; while (scan.hasNext()){ String name = scan.next(); int age = scan.nextInt(); if (age > maxAge) { maxAge = age; oldest = name; } UI.println(“Oldest is %s (%d)\n”, oldest, maxAge); } catch (IOException e) { UI.printf(“File failure: %s\n”, e); } } False when at end of file name first; age second Note: name must be just one token!! James 33 Helen 25 John 73 pondy 19
© Peter Andreae COMP : 4 Handling multiple items on line Sometimes you can tell where the line ends: /**Sums counts of items in file of items and counts*/ public void printItemCounts(){ try { Scanner scan = new Scanner(new File(“data.txt")); while (scan.hasNext()){ String item = scan.next(); int lineTot = 0; while (scan.hasNextInt()) { lineTot = lineTot + scan.nextInt(); } UI.println(item + “: ” + lineTot); } } catch (IOException e) { UI.printf(“File failure: %s\n”, e); } } biscuits cake fruit beans biscuits: 88 cake: 10 fruit: 235 beans: 33
© Peter Andreae COMP : 5 Reading files line by line Sometimes can’t tell where ends of lines are: may need to read a line at a time, then process: /**Adds up numbers on each line of a file */ public void addCounts(){ try { Scanner scan = new Scanner(new File(“data.txt")); while (scan.hasNext()){ String line = scan.nextLine(); Scanner lineSc = new Scanner(line); int lineTot = 0; while (lineSc.hasNextInt()) { lineTot = lineTot + lineSc.nextInt(); } UI.println(lineTot); } } catch (IOException e) { UI.printf(“File failure: %s\n”, e); } } Wrapping a Scanner around a String, Lets you “read” values from the String
© Peter Andreae COMP : 6 Writing to a File Open a File Wrap it in a new PrintStream object. Call print, println, or printf on it. Close the file : PrintStream out = new PrintStream(new File("Square-table.txt")); int n=1; out.println("Number\tSquare"); while ( n <= 1000 ) { out.printf("%6d\t%8d\n", n, n*n); n = n+1; } out.close() : File Object Just like printing to UI PrintStream Object
© Peter Andreae COMP : 7 Checking if files exist Can check that file exists before trying to read: /** Make a copy of a file with line numbers */ public void lineNumber(String fname){ File infile = new File(fname); if (infile.exists()) { File outfile = new File(“numbered-” +fname) try { PrintStream out = new PrintStream(outfile); Scanner sc = new Scanner ( infile ); int num = 0; while (sc.hasNext()) { outfile.println((num++) + “: ” + sc.nextLine() ); } out.close(); sc.close(); } catch (IOException e) {UI.printf(“File failure %s\n”, e);} }
© Peter Andreae COMP : 8 Passing an open scanner First method: Just opens and closes the file public void countTokensInFile(String fname){ try { Scanner scan = new Scanner (new File(fname)); int numTokens = this.countTkns(scan); UI.printf(“%s has %d tokens\n”, fname, numTokens); sc.close(); } catch (Exception e) {UI.printf(“File failure %s\n”, e);} } Second Method: Just reads from the file and counts public int countTkns (Scanner sc){ int count = 0; while (sc.hasNext()) { sc.next(); // throws result away ! count = count+1; } return count; }
© Peter Andreae COMP : 9 UIFileChooser So far, we’ve specified which file to open and read or write. eg: File myfile = new File(“input.txt”); How can we allow the user to choose a file ? UIFileChooser class (part of ecs100 library, like UI) MethodWhat it doesReturns open() Opens dialog box; user can select an existing file to open. Returns name of file or null if user cancelled. String open(String title) Same as open(), but with specified title;String save() Opens dialog box; user can select file (possibly new) to save to. Returns name of file, or null if the user cancelled. String save(String title) Same as save(), but with specified title.String
© Peter Andreae COMP : 10 /** allow user to choose and open an existing file*/ String filename = UIFileChooser.open(); File myfile = new File(filename); Scanner scan = new Scanner(myfile); OR Scanner scan = new Scanner(new File(UIFileChooser.open())); /** allow user to choose and open an existing file, specifies a title for dialog box*/ File myfile = new File(UIFileChooser.open(“Choose a file to copy”)); Scanner scan = new Scanner(myfile); Two “open” methods in one class ? Overloading : two methods in the same class can have the same name as long as they have different parameters. Using UIFileChooser methods: open
© Peter Andreae COMP : 11 Using UIFileChooser methods: save /** allow user to choose and save to a (new/existing) file*/ String filename = UIFileChooser.save(); File myfile = new File(filename); PrintStream ps = new PrintStream(myfile); OR PrintStream ps = new PrintStream(new File(UIFileChooser.save())); /** allow user to choose and save to a (new/existing) file, Specifies a title for dialog box */ File myfile = new File(UIFileChooser.save(“File to save data in”)); PrintStream ps = new PrintStream(myfile);
© Peter Andreae COMP : 12 More about static /** Play a guessing game with the user*/ public class GuessingGame{ public static final int maxValue = 40; /** plays rounds of game*/ public void playGame ( ){ … } /** plays one round of guessing game */ public int playRound ( ){ … } /** main method */ public static void main(String[ ] args){ GuessingGame game = new GuessingGame(); game.playGame(); } static means “Belongs to class as a whole, Not to individual objects”
© Peter Andreae COMP : 13 Static vs non-static methods The textbook (ch 1 – 3) only used the main method; The lectures used ordinary methods, but not main Why? If you don’t have BlueJ, you can’t run a program without main ⇒ Textbook used main With BlueJ, you can run individual methods in a program simpler methods clearer understanding of objects and methods. good for testing programs ⇒ This course won’t use main much, and will always be minimal.
© Peter Andreae COMP : 14 More static methods: Static methods are methods that don’t need an object: Methods in the Math class are static methods: Math.min(…) Math.max(…) Math.random() Math.sqrt(…) Methods in the UI class are static methods: UI.drawRect(…) UI.println(…) UI.askInt(…) None of these methods need an object to be created first. Methods are called on the Class itself.
© Peter Andreae COMP : 15 Coercion Mismatching types: double num = scan.nextInt( ); int number = scan.nextDouble( ); Can't do this double squareroot = Math.sqrt(25); but sqrt wants double String name = “number-” + num; Java will “coerce” a value to the needed type if it can: eg If a method needs a double and is given an int: If an int is assigned to a double variable If “adding” any value to a String But only if it does not lose any information: WON’T coerce a double to an int WON’T coerce a String to a number, or vice versa except when “adding” a number to a String WON’T coerce any object to a mismatching type except when printing or “adding” to a String
© Peter Andreae COMP : 16 Casting Where it makes sense to convert a value into another type, but some information may be lost... You can sometimes “cast” the value to the other type: int number = (int) Math.sqrt(49.5); float red = (float) Math.random(); casting a double to an int will lose the fractional part and may mess up the value if the number is too big! Not everything can be cast to everything else! Scanner scan = ( Scanner ) (new File(“data.txt”)); (〈 new type 〉)〈 expression 〉