Presentation is loading. Please wait.

Presentation is loading. Please wait.

CPSC150 JavaLynn Lambert Week 13 Rest of Guis (from Bluej web page) mainExceptions.

Similar presentations


Presentation on theme: "CPSC150 JavaLynn Lambert Week 13 Rest of Guis (from Bluej web page) mainExceptions."— Presentation transcript:

1 CPSC150 JavaLynn Lambert Week 13 Rest of Guis (from Bluej web page) mainExceptions

2 CPSC150 Java Lynn Lambert Rest of GUIs Overview of Swing Overview of Swing (from Dr. Flores’ notes from Liang) JOptionPane example JOptionPane example MenuBars MenuBars

3 CPSC150 Java Lynn Lambert Java GUI The Java GUI packages GUI classes are found in two packages: AWT (Abstract Windows Toolkit) Swing Swing components are based on AWT classes Java 2 released Swing as an alternative to AWT AWT uses platform-specific GUI components Swing is less reliant on platform-specific components more less heavyweight components AWT lightweight components Swing reliance on platform-specific GUI components

4 CPSC150 Java Lynn Lambert Java GUI The Java GUI inheritance hierarchy Object Color Container Component LayoutManager Panel Window Applet Frame Dialog JComponent JApplet JFrame JDialog lightweight heavyweight Swing AWT

5 CPSC150 Java Lynn Lambert Java GUI The Java GUI inheritance hierarchy JComponent JMenuBar AbstractButton JScrollPane JPanel JTextComponent JLabel JComboBox JMenuItem JButton JTextArea JTextField JPasswordField … etc. Swing …

6 CPSC150 Java Lynn Lambert Rest of GUIs Overview of Swing Overview of Swing JOptionPane example JOptionPane example (from Dr. Flores and from Chapter 11) MenuBars MenuBars

7 CPSC150 Java Lynn Lambert The JOptionPane Class Java comes with simple ready-made dialogs showConfirmDialog int result = JOptionPane.showConfirmDialog( frame, "These are your options", "confirm dialog", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE ); int result = JOptionPane.showConfirmDialog( frame, "These are your options", "confirm dialog", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE ); parent frame message option type (one of): DEFAULT_OPTION YES_NO_OPTION YES_NO_CANCEL_OPTION OK_CANCEL_OPTION option type (one of): DEFAULT_OPTION YES_NO_OPTION YES_NO_CANCEL_OPTION OK_CANCEL_OPTION title message type result value (one of): OK_OPTION YES_OPTION NO_OPTION CANCEL_OPTION CLOSE_OPTION result value (one of): OK_OPTION YES_OPTION NO_OPTION CANCEL_OPTION CLOSE_OPTION Ready-to-use Dialogs

8 CPSC150 Java Lynn Lambert The JOptionPane Class Java comes with simple ready-made dialogs showOptionDialog String[] options = {"BMW","Mini","Mustang","Porsche"}; int result = JOptionPane.showOptionDialog( frame, "Choose a car:", "options dialog", -1, new ImageIcon("car.gif"), options, options[1]); String[] options = {"BMW","Mini","Mustang","Porsche"}; int result = JOptionPane.showOptionDialog( frame, "Choose a car:", "options dialog", -1, new ImageIcon("car.gif"), options, options[1]); parent frame option type title message result value (one of): 0…options.length-1 CLOSE_OPTION result value (one of): 0…options.length-1 CLOSE_OPTION message type icon options selection (  options) options one label per button options one label per button Ready-to-use Dialogs

9 CPSC150 Java Lynn Lambert Rest of GUIs Overview of Swing Overview of Swing JOptionPane example JOptionPane example MenuBars MenuBars (from BlueJ book notes)

10 CPSC150 Java Lynn Lambert Adding menus JMenuBar JMenuBar Displayed below the title. Displayed below the title. Contains the menus. Contains the menus. JMenu JMenu e.g. File. Contains the menu items. e.g. File. Contains the menu items. JMenuItem JMenuItem e.g. Open. Individual items. e.g. Open. Individual items.

11 CPSC150 Java Lynn Lambert private void makeMenuBar(JFrame frame) { JMenuBar menubar = new JMenuBar(); frame.setJMenuBar(menubar); // create the File menu JMenu fileMenu = new JMenu("File"); menubar.add(fileMenu); JMenuItem openItem = new JMenuItem("Open"); fileMenu.add(openItem); JMenuItem quitItem = new JMenuItem("Quit"); fileMenu.add(quitItem); }

12 CPSC150 Java Lynn Lambert Anonymous action listener JMenuItem openItem = new JMenuItem("Open"); openItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openFile(); } });

13 CPSC150 Java Lynn Lambert Anonymous class elements openItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { openFile(); } ); Anonymous object creation Actual parameter Class definition

14 CPSC150 Java Lynn Lambert Struts and Glue Invisible components used as spacing. Invisible components used as spacing. Available from the Box class. Available from the Box class. Strut: fixed size. Strut: fixed size. Component createHorizontalStrut(int width) Component createHorizontalStrut(int width) Component createVerticalStrut(int height) Component createVerticalStrut(int height) Glue: fills available space. Glue: fills available space. Component createHorizontalGlue() Component createHorizontalGlue() Component createVerticalGlue() Component createVerticalGlue()

15 CPSC150 Java Lynn Lambert Pushing a menu to the right menu = new JMenu("File"); menubar.add(menu); menu = new JMenu("Filter"); menubar.add(menu); menubar.add(Box.createHorizontalGlue()); menu = new JMenu("Help"); menubar.add(menu); Glue (invisible)

16 CPSC150 Java Lynn Lambert Buttons and nested layouts (for information only) A GridLayout inside a FlowLayout inside a BorderLayout.

17 CPSC150 Java Lynn Lambert Borders (for information only) Used to add decoration around components. Used to add decoration around components. Defined in javax.swing.border Defined in javax.swing.border BevelBorder, CompoundBorder, EmptyBorder, EtchedBorder, TitledBorder. BevelBorder, CompoundBorder, EmptyBorder, EtchedBorder, TitledBorder.

18 CPSC150 Java Lynn Lambert Adding spacing (for information only) JPanel contentPane = (JPanel)frame.getContentPane(); contentPane.setBorder(new EmptyBorder(6, 6, 6, 6)); // Specify the layout manager with nice spacing contentPane.setLayout(new BorderLayout(6, 6)); imagePanel = new ImagePanel(); imagePanel.setBorder(new EtchedBorder()); contentPane.add(imagePanel, BorderLayout.CENTER);

19 CPSC150 Java Lynn Lambert Other components (for information only) Slider Slider Spinner Spinner Tabbed pane Tabbed pane Scroll pane Scroll pane

20 CPSC150 JavaLynn Lambert Week 13 Rest of Guis (from Bluej web page) mainExceptions

21 CPSC150 Java Lynn Lambert main Java programs may be run outside BlueJ (and outside of any IDE) Java programs may be run outside BlueJ (and outside of any IDE) Java programs are run on a JVM Java programs are run on a JVM Java programs run outside of blueJ start with the method called main Java programs run outside of blueJ start with the method called main

22 CPSC150 Java Lynn Lambert Compiling Java programs Files created in BlueJ can be run ins or outside or Bluej. (Files created outside of BlueJ need “Open non-BlueJ”) Files created in BlueJ can be run ins or outside or Bluej. (Files created outside of BlueJ need “Open non-BlueJ”) To compile outside of Bluej, type in terminal window: To compile outside of Bluej, type in terminal window: javac nameofprogram.java javac nameofprogram.java syntax errors will be reported in terminal window syntax errors will be reported in terminal window when syntax error free,.class file will be created (e.g., nameofprogram.java) when syntax error free,.class file will be created (e.g., nameofprogram.java) NOTE: name of class MUST be the same as the name of the file (in BlueJ and out) NOTE: name of class MUST be the same as the name of the file (in BlueJ and out)

23 CPSC150 Java Lynn Lambert Running Java programs To run outside of BlueJ (on JVM), type: To run outside of BlueJ (on JVM), type: java nameofprogram where nameofprogram is file name except.class part where nameofprogram is file name except.class part NOT java nameofprogram.class NOT java nameofprogram.class java nameofprogram.class results in the following error: results in the following error: Exception in thread "main" java.lang.NoClassDefFoundError: nameofprogram/class

24 CPSC150 Java Lynn Lambert main public static void main(String[] args) { // usually not much here. create an object, and go } so it can be called outside the class so an object doesn’t have to be created in order to use it in case arguments on command line (e.g., cp file1 file2)

25 CPSC150 Java Lynn Lambert main method rules Because it is static, all methods that call it must be static. Because it is static, all methods that call it must be static. So, don’t have many methods call it So, don’t have many methods call it Create an object, and go from there Create an object, and go from there Sometimes, especially with GUIs, no return from main. Sometimes, especially with GUIs, no return from main. ctrl-c to end program ctrl-c to end program

26 CPSC150 Java Lynn Lambert main examples All 150lab examples have main All 150lab examples have main compile these outside compile these outside run them run them Exercise: Create a main method for your Rainfall program (program 3). Create a rainfall object in main and call it. Run the program. Exercise: Create a main method for your Rainfall program (program 3). Create a rainfall object in main and call it. Run the program.

27 CPSC150 Java Lynn Lambert more on static: Math library Math library contains methods to do math Math library contains methods to do math log, max, sqrt, round, abs, etc. log, max, sqrt, round, abs, etc. All methods are static All methods are static Why? Why?

28 CPSC150 Java Lynn Lambert class Myclass { private double mynbr; public Myclass(double val) { mynbr = val; } public double getSqrt( ) { return Math.sqrt(mynbr); }} With Math Static methods

29 CPSC150 Java Lynn Lambert With Math non-static methods class Myclass { private double mynbr; public Myclass(double val) {mynbr = val;} public double getSqrt( ) { Math stupidobject = new Math( ); // create object in order to use sqrt method. no other reason. // object is not being used. NOT like changeColor method – // changeColor is being done on object. OR, getTitle for Item. return suptidobject.sqrt(mynbr); }}

30 CPSC150 Java Lynn Lambert Static vs non-static Most methods are done for the objects. should be non-static Most methods are done for the objects. should be non-static Some methods exist for the class. should be static Some methods exist for the class. should be static Any methods main calls must be static Any methods main calls must be static Lesson: main shouldn’t call many methods Lesson: main shouldn’t call many methods

31 CPSC150 JavaLynn Lambert Week 13 Rest of Guis (from Bluej web page) mainExceptions (from slides provided by textbook web site)

32 CPSC150 JavaLynn Lambert Handling errors 2.1

33 CPSC150 Java Lynn Lambert Some causes of error situations Incorrect implementation. Incorrect implementation. Does not meet the specification. Does not meet the specification. Inappropriate object request. Inappropriate object request. E.g., invalid index. E.g., invalid index. Inconsistent or inappropriate object state. Inconsistent or inappropriate object state. E.g. arising through class extension. E.g. arising through class extension.

34 CPSC150 Java Lynn Lambert Not always programmer error Errors often arise from the environment: Errors often arise from the environment: Incorrect URL entered. Incorrect URL entered. Network interruption. Network interruption. File processing is particular error-prone: File processing is particular error-prone: Missing files. Missing files. Lack of appropriate permissions. Lack of appropriate permissions.

35 CPSC150 Java Lynn Lambert Exploring errors Explore error situations through the address-book projects. Explore error situations through the address-book projects. Two aspects: Two aspects: Error reporting. Error reporting. Error handling. Error handling.

36 CPSC150 Java Lynn Lambert Issues to be addressed How much checking by a server on method calls? How much checking by a server on method calls? How to report errors? How to report errors? What if no user at the other end (e.g., GUI)? How can a client anticipate failure? How can a client anticipate failure? How should a client deal with failure? How should a client deal with failure?

37 CPSC150 Java Lynn Lambert An example Create an AddressBook object. Create an AddressBook object. Try to remove an entry. Try to remove an entry. A runtime error results. A runtime error results. Whose ‘fault’ is this? Whose ‘fault’ is this? Anticipation and prevention are preferable to apportioning blame. Anticipation and prevention are preferable to apportioning blame.

38 CPSC150 Java Lynn Lambert Argument values Arguments represent a major ‘vulnerability’ for a server object. Arguments represent a major ‘vulnerability’ for a server object. Constructor arguments initialize state. Constructor arguments initialize state. Method arguments often contribute to behavior. Method arguments often contribute to behavior. Argument checking is one defensive measure. Argument checking is one defensive measure.

39 CPSC150 Java Lynn Lambert Checking the key public void removeDetails(String key) { if(keyInUse(key)) { ContactDetails details = (ContactDetails) book.get(key); book.remove(details.getName()); book.remove(details.getPhone()); numberOfEntries--; }

40 CPSC150 Java Lynn Lambert Server error reporting How to report illegal arguments? How to report illegal arguments? To the user? To the user? Is there a human user? Is there a human user? Can they solve the problem? Can they solve the problem? To the client object? To the client object? Return a diagnostic value Return a diagnostic value

41 CPSC150 Java Lynn Lambert Returning a diagnostic (Exception handling without using Java’s exception handling) public boolean removeDetails(String key) { if(keyInUse(key)) { ContactDetails details = (ContactDetails) book.get(key); book.remove(details.getName()); book.remove(details.getPhone()); numberOfEntries--; return true; } else { return false; }

42 CPSC150 Java Lynn Lambert Client responses Test the return value. Test the return value. Attempt recovery on error. Attempt recovery on error. Avoid program failure. Avoid program failure. Ignore the return value. Ignore the return value. Cannot be prevented. Cannot be prevented. Likely to lead to program failure. Likely to lead to program failure. Create something client cannot ignore: Create something client cannot ignore: an exception an exception

43 CPSC150 Java Lynn Lambert Exception-throwing principles Exceptions are part of many languages, central to Java. Exceptions are part of many languages, central to Java. A special language feature. A special language feature. No ‘special’ return value needed. No ‘special’ return value needed. Errors cannot be ignored in the client. Errors cannot be ignored in the client. The normal flow-of-control is interrupted. The normal flow-of-control is interrupted. Specific recovery actions are encouraged. Specific recovery actions are encouraged.

44 CPSC150 Java Lynn Lambert Exceptions Exceptions are “thrown” by the method finding the problem Exceptions are “thrown” by the method finding the problem Exceptions are “caught” by the method dealing with the problem Exceptions are “caught” by the method dealing with the problem maintains integrity and decoupling maintains integrity and decoupling

45 CPSC150 Java Lynn Lambert Throwing an exception /** * Look up a name or phone number and return the * corresponding contact details. * @param key The name or number to be looked up. * @return The details corresponding to the key, * or null if there are none matching. * @throws NullPointerException if the key is null. */ public ContactDetails getDetails(String key) { if(key == null){ throw new NullPointerException( "null key in getDetails"); } return (ContactDetails) book.get(key); }

46 CPSC150 Java Lynn Lambert Throwing an exception An exception object is constructed: An exception object is constructed: new ExceptionType("..."); new ExceptionType("..."); The exception object is thrown: The exception object is thrown: throw... throw... Javadoc documentation: Javadoc documentation: @throws ExceptionType reason @throws ExceptionType reason

47 CPSC150 Java Lynn Lambert The exception class hierarchy

48 CPSC150 Java Lynn Lambert Exception categories Checked exceptions Checked exceptions Subclass of Exception Subclass of Exception Use for anticipated failures. Use for anticipated failures. Where recovery may be possible. Where recovery may be possible. Often not a programming problem (e.g., file not found) Often not a programming problem (e.g., file not found) Unchecked exceptions Unchecked exceptions Subclass of RuntimeException Subclass of RuntimeException Use for unanticipated failures. Use for unanticipated failures. Where recovery is unlikely. Where recovery is unlikely. Often, a programming problem (e.g., index out of bounds) Often, a programming problem (e.g., index out of bounds) Third category: errors Third category: errors

49 CPSC150 Java Lynn Lambert The effect of an exception The throwing method finishes prematurely. The throwing method finishes prematurely. No return value is returned. No return value is returned. Control does not return to the client’s point of call. Control does not return to the client’s point of call. So the client cannot carry on regardless. So the client cannot carry on regardless. A client may ‘catch’ an exception. A client may ‘catch’ an exception.

50 CPSC150 Java Lynn Lambert Unchecked exceptions Use of these is ‘unchecked’ by the compiler. Use of these is ‘unchecked’ by the compiler. Cause program termination if not caught. Cause program termination if not caught. This is the normal practice. This is the normal practice. IllegalArgumentException is a typical example. IllegalArgumentException is a typical example.

51 CPSC150 Java Lynn Lambert Argument checking public ContactDetails getDetails(String key) { if(key == null) { throw new NullPointerException( "null key in getDetails"); } if(key.trim().length() == 0) { throw new IllegalArgumentException( "Empty key passed to getDetails"); } return (ContactDetails) book.get(key); }

52 CPSC150 Java Lynn Lambert Preventing object creation public ContactDetails(String name, String phone, String address) { if(name == null) { name = ""; } if(phone == null) { phone = ""; } if(address == null) { address = ""; } this.name = name.trim(); this.phone = phone.trim(); this.address = address.trim(); if(this.name.length() == 0 && this.phone.length() == 0) { throw new IllegalStateException( "Either the name or phone must not be blank."); }

53 CPSC150 Java Lynn Lambert public class Myexcept { private int x; public Myexcept() { x = 0; } { x = 0; } public int sampleMethod(int y) { if (y == 0) { throw new ArithmeticException( throw new ArithmeticException( "in SampleMethod, y, a denominator, is 0"); "in SampleMethod, y, a denominator, is 0"); } y= x /y; y= x /y; return y; return y; } // …

54 CPSC150 Java Lynn Lambert public static void main(String args[ ]) public static void main(String args[ ]) { Myexcept m = new Myexcept(); Myexcept m = new Myexcept(); System.out.println("m with 4 is " + m.sampleMethod(4)); System.out.println("m with 4 is " + m.sampleMethod(4)); System.out.println("m with 0 is " + System.out.println("m with 0 is " + m.sampleMethod(0)); m.sampleMethod(0)); System.out.println("all done"); System.out.println("all done"); } // end main } // end main } // end class

55 CPSC150 Java Lynn Lambert public static void main(String args[ ]) { except m = new except(); except m = new except(); System.out.println("m with 4 is " + System.out.println("m with 4 is " + m.sampleMethod(4)); m.sampleMethod(4)); try { try { System.out.println("m with 0 is " + System.out.println("m with 0 is " + m.sampleMethod(0)); m.sampleMethod(0)); } catch (ArithmeticException e) { catch (ArithmeticException e) { System.out.println("don't call sample method with 0"); System.out.println("don't call sample method with 0"); } System.out.println("all done"); System.out.println("all done"); }

56 CPSC150 Java Lynn Lambert public class Test { public static void main(String args[]) { int n = 0; String s = null; boolean valid = false; while (!valid) try { s = JOptionPane.showInputDialog( null, "Enter an integer:" ); n = Integer.parseInt( s ); valid = true; } catch(Exception e) { if (s == null) break; else JOptionPane.showMessageDialog( null, "Enter a valid number" ); } if (valid) JOptionPane.showMessageDialog( null, "The number is " + n ); }

57 CPSC150 Java Lynn Lambert Checked Exceptions Previous examples all unchecked exceptions Previous examples all unchecked exceptions unchecked exceptions should not happen; mostly result in program termination unchecked exceptions should not happen; mostly result in program termination Checked exceptions are meant to be caught. Checked exceptions are meant to be caught. The compiler ensures that their use is tightly controlled. The compiler ensures that their use is tightly controlled. In both server and client. In both server and client. Used properly, failures may be recoverable. Used properly, failures may be recoverable.

58 CPSC150 Java Lynn Lambert Some Checked Exceptions ClassNotFoundException ClassNotFoundException ClassNotFoundException IOException IOException IOException NoSuchFieldException NoSuchFieldException NoSuchFieldException ServerNotActiveException ServerNotActiveException ServerNotActiveException UnsupportedFlavorException UnsupportedFlavorException UnsupportedFlavorException

59 CPSC150 Java Lynn Lambert The throws clause Methods throwing a checked exception must include a throws clause: public void saveToFile(String destinationFile) throws IOException Methods throwing a checked exception must include a throws clause: public void saveToFile(String destinationFile) throws IOException (NOT throw) throw is when the exception is thrown (NOT throw) throw is when the exception is thrown

60 CPSC150 Java Lynn Lambert throws must include throws in methods that throw checked exceptions must include throws in methods that throw checked exceptions how do I know? how do I know? javadoc/syntax errors javadoc/syntax errors

61 CPSC150 Java Lynn Lambert The try statement Clients catching an exception must protect the call with a try statement: try { Protect one or more statements here. } catch(Exception e) { Report and recover from the exception here. } Clients catching an exception must protect the call with a try statement: try { Protect one or more statements here. } catch(Exception e) { Report and recover from the exception here. }

62 CPSC150 Java Lynn Lambert The try statement try{ addressbook.saveToFile(filename); tryAgain = false; } catch(IOException e) { System.out.println("Unable to save to " + filename); tryAgain = true; } 1. Exception thrown from here 2. Control transfers to here

63 CPSC150 Java Lynn Lambert Catching multiple exceptions try in order that they appear try {... ref.process();... } catch(EOFException e) { // Take action on an end-of-file exception.... } catch(FileNotFoundException e) { // Take action on a file-not-found exception.... }

64 CPSC150 Java Lynn Lambert The finally clause try { Protect one or more statements here. } catch(Exception e) { Report and recover from the exception here. } finally { Perform any actions here common to whether or not an exception is thrown. }

65 CPSC150 Java Lynn Lambert The finally clause A finally clause is executed even if a return statement is executed in the try or catch clauses. A finally clause is executed even if a return statement is executed in the try or catch clauses. A uncaught or propagated exception still exits via the finally clause. A uncaught or propagated exception still exits via the finally clause.

66 CPSC150 Java Lynn Lambert Error recovery Clients should take note of error notifications. Clients should take note of error notifications. Check return values. Check return values. Don’t ‘ignore’ exceptions. Don’t ‘ignore’ exceptions. Include code to attempt recovery. Include code to attempt recovery. Will often require a loop. Will often require a loop.

67 CPSC150 Java Lynn Lambert Attempting recovery // Try to save the address book. boolean successful = false; int attempts = 0; do { try { addressbook.saveToFile(filename); successful = true; } catch(IOException e) { System.out.println("Unable to save to " + filename); attempts++; if(attempts < MAX_ATTEMPTS) { filename = an alternative file name; } } while(!successful && attempts < MAX_ATTEMPTS); if(!successful) { Report the problem and give up; }

68 CPSC150 Java Lynn Lambert Error avoidance Clients can often use server query methods to avoid errors. Clients can often use server query methods to avoid errors. More robust clients mean servers can be more trusting. More robust clients mean servers can be more trusting. Unchecked exceptions can be used. Unchecked exceptions can be used. Simplifies client logic. Simplifies client logic. May increase client-server coupling. May increase client-server coupling.

69 CPSC150 JavaLynn Lambert Files Chapter 12 continued

70 CPSC150 Java Lynn Lambert Text input-output: tie to exceptions Input-output is particularly error-prone. Input-output is particularly error-prone. It involves interaction with the external environment. It involves interaction with the external environment. The java.io package supports input-output. The java.io package supports input-output. java.io.IOException is a checked exception. java.io.IOException is a checked exception. cannot do files without exceptions cannot do files without exceptions

71 CPSC150 Java Lynn Lambert Files To use files, use File class To use files, use File class File class can’t read/write File class can’t read/write To read/write files, use Reader/Writer classes To read/write files, use Reader/Writer classes File input can be text-based (what we’ll do), stream-based File input can be text-based (what we’ll do), stream-based

72 CPSC150 Java Lynn Lambert Readers, writers, streams Readers and writers deal with textual input. Readers and writers deal with textual input. Based around the char type. Based around the char type. Streams deal with binary data. Streams deal with binary data. Based around the byte type. Based around the byte type. The address-book-io project illustrates textual IO. The address-book-io project illustrates textual IO.

73 CPSC150 Java Lynn Lambert Text output Use the FileWriter class. Use the FileWriter class. Tie File object to diskfile name Tie File object to diskfile name Open a FileWriter; tie to File. Open a FileWriter; tie to File. Write to the FileWriter. Write to the FileWriter. Close the FileWriter. Close the FileWriter. Failure at any point results in an IOException. Failure at any point results in an IOException.

74 CPSC150 Java Lynn Lambert Text output try { FileWriter writer = new FileWriter("name of file"); while(there is more text to write) {... writer.write(next piece of text);... } writer.close(); } catch(IOException e) { something went wrong with accessing the file }

75 CPSC150 Java Lynn Lambert Text input Use the FileReader class. Use the FileReader class. Augment with BufferedReader for line- based input. Augment with BufferedReader for line- based input. Open a file. Open a file. Read from the file. Read from the file. Close the file. Close the file. Failure at any point results in an IOException. Failure at any point results in an IOException.

76 CPSC150 Java Lynn Lambert Text input try { BufferedReader reader = new BufferedReader( new FileReader("filename")); String line = reader.readLine(); while(line != null) { do something with line line = reader.readLine(); } reader.close(); } catch(FileNotFoundException e) { the specified file could not be found } catch(IOException e) { something went wrong with reading or closing }

77 CPSC150 Java Lynn Lambert Write a program to count number of lines in a file and write the number to an output file java countlines myinfile.txt myoutfile.txt would return 2 if file is: This is a file with two lines. myinfile.txt

78 CPSC150 Java Lynn Lambert import java.io.*; public class countlines { // all methods that do something inserted here public static void main(String[] args) public static void main(String[] args) { if (args.length != 2) if (args.length != 2) { System.out.println("to run, type: 'countlines filein fileout'"); System.out.println("to run, type: 'countlines filein fileout'"); System.exit(1); System.exit(1); } // create a new countline object with first arg as input file, second as output countlines cl = new countlines(args[0], args[1]); countlines cl = new countlines(args[0], args[1]);}}

79 CPSC150 Java Lynn Lambert // constructor // constructor public countlines(String filein, String fileout) { try { try { int countwords = readfrom(filein); int countwords = readfrom(filein); writeto(fileout, countwords); writeto(fileout, countwords); } catch (IOException e) { catch (IOException e) { // will catch any IO exception not caught by readfrom and writeto System.out.println("Problems with IO. Program aborted without successful write."); System.out.println("Problems with IO. Program aborted without successful write."); } }

80 CPSC150 Java Lynn Lambert // file output. method called from constructor public void writeto(String fileout, int nbrlines) throws IOException // must have “throws IOException” even though // no “throw statement” { File outfile = new File(fileout); File outfile = new File(fileout); FileWriter fw = new FileWriter(outfile); FileWriter fw = new FileWriter(outfile); // usually a loop to write out all information // usually a loop to write out all information // write to writer, not file // write to writer, not file fw.write("There were " + nbrlines + " lines in the input file."); fw.write("There were " + nbrlines + " lines in the input file."); fw.close(); fw.close(); }

81 CPSC150 Java Lynn Lambert public int readfrom(String filename) throws IOException public int readfrom(String filename) throws IOException { int countlines = 0; int countlines = 0; try { try { File infile = new File(filename); File infile = new File(filename); BufferedReader reader = new BufferedReader(new FileReader(infile)); BufferedReader reader = new BufferedReader(new FileReader(infile)); String line; String line; line = reader.readLine(); line = reader.readLine(); while (line != null) { while (line != null) { System.out.println(line); // for debugging only; System.out.println(line); // for debugging only; countlines++; countlines++; line = reader.readLine(); line = reader.readLine(); } reader.close(); reader.close(); } catch (FileNotFoundException e) { catch (FileNotFoundException e) { System.out.println("The input file was not there"); System.out.println("The input file was not there"); } return countlines; return countlines; }

82 CPSC150 Java Lynn Lambert Other Wrappers Can break string read up using StringTokenizer Can break string read up using StringTokenizer Can read non-text files with FileReader and Tokenizer (breaks fields up to be read) Can read non-text files with FileReader and Tokenizer (breaks fields up to be read)


Download ppt "CPSC150 JavaLynn Lambert Week 13 Rest of Guis (from Bluej web page) mainExceptions."

Similar presentations


Ads by Google