Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More on Files COMP 102 # 14.

Slides:



Advertisements
Similar presentations
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Creating and using Objects.
Advertisements

© Xiaoying Gao, Peter Andreae COMP :1 Term test Grade Marks No of students “A” range 36 ~45 53 “B” range29.25~ “C” range 22.5~2941 “D” range
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with Methods COMP.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: File Output; Reference Semantics reading: , 7.1, 4.3, 3.3 self-checks:
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Java Programs COMP 102 #3.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Review COMP 102 #
Week 14 - Monday.  What did we talk about last time?  Image manipulation  Inheritance.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Program Elements and Syntax.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Arrays COMP 102 # T1.
Applications in Java Towson University *Ref:
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More 2D arrays COMP 102 #27.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Arrays with meaningful indices.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Call a Method,
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Patterns with.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 More Collections: Queues,
Copyright 2010 by Pearson Education Building Java Programs Chapter 6 Lecture 6-2: Line-Based File Input reading:
1 Hours question Given a file hours.txt with the following contents: 123 Kim Eric Stef
2011-T1 Lecture 13 School of Engineering and Computer Science, Victoria University of Wellington  Rashina Hoda and Peter Andreae COMP 102 Rashina Hoda.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington 2D arrays COMP 102 # T1.
Topic 19 file input, line based Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
CSci 111 – computer Science I Fall 2014 Cynthia Zickos WRITING A SIMPLE PROGRAM IN JAVA.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Files COMP 102.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington “For each” & Patterns with.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Exercise, printf,
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More Event-driven Input TextFields,
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Classes, Objects, Fields,
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Types and Interfaces COMP.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Creating Objects.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Loops and Input COMP 102 #
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with Classes and.
Week 14 - Monday.  What did we talk about last time?  Inheritance.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More on Files COMP 102 # 14.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Fields, Constructors.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Loops and Input COMP 102 #
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists COMP 102 # T1.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Types and Interfaces COMP.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington 2D arrays COMP 102 # T1.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Creating Objects.
Building Java Programs Chapter 6 Lecture 6-2: Line-Based File Input reading:
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with Classes and.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Java Programs COMP 102 #3.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists: varying size arrays.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists: varying size arrays.
Files Review For output to a file: –FileOutputStream variable initialized to filename (String) and append/not append (boolean) –PrintWriter variable initialized.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More 2D arrays COMP 102 #27.
2011-T1 Lecture 12 School of Engineering and Computer Science, Victoria University of Wellington  Rashina Hoda and Peter Andreae COMP 102 Rashina Hoda.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with While loops.
© Peter Andreae Java Programs COMP 102 # T1 Peter Andreae Computer Science Victoria University of Wellington.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Arrays COMP 102 # T1.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Dealing with Files COMP 102.
CS1020 Data Structures and Algorithms I Lecture Note #16 File Processing.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More Event-driven Input COMP.
Files The UI text pane window is transient:
Building Java Programs
Writing to a File Open a File Wrap it in a new PrintStream object.
File Input and Output TOPICS File Input Exception Handling File Output.
Week 14 - Wednesday CS 121.
File Input and Output TOPICS File Input Exception Handling File Output.
Input/output (I/O) import java.io.*;
Building Java Programs
CSC1401 Input and Output (with Files)
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Presentation transcript:

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 〉