120 likes | 245 Views
More API. CSCE 190 – Java Instructor: Joel Gompert July 23, 2004. Converting From Strings to numbers. String s1 = "3546"; int i=0; try { i = Integer.parseInt(s1); } catch(NumberFormatException e) { System.out.println("Not a valid number."); }. Exception Handling. try {
E N D
More API CSCE 190 – Java Instructor: Joel Gompert July 23, 2004
Converting From Strings to numbers String s1 = "3546"; int i=0; try { i = Integer.parseInt(s1); } catch(NumberFormatException e) { System.out.println("Not a valid number."); }
Exception Handling try { // code that may throw exceptions }
Exception Handling try { // code that may throw exceptions } catch(exception_type e) { // code to handle an exception }
Exception Handling try { // code that may throw exceptions } catch(exception_type e) { // code to handle an exception } finally { // code always to be executed after the try block }
Converting from String to float String s2 = "3485.934"; float f=0; try { f = Float.parseFloat(s2); } catch(NumberFormatException e) { System.out.println("Not a valid number."); }
File Input/Output • File I/O classes in the API • Characters • java.io.FileReader • java.io.FileWriter • Bytes • java.io.FileInputStream • java.io.FileOutputStream • java.io.PrintWriter • Can make outputting text easier • java.io.StreamTokenizer • Can make inputting text eaiser
File Output Example FileWriter fwriter; try { fwriter = new FileWriter("test.txt"); } catch(IOException e) { System.out.println("Unable to open file."); return; } PrintWriter pwriter = new PrintWriter(fwriter); int x = 42; pwriter.println("This is a test"); pwriter.println("Let's output a number: " + x); try { fwriter.close(); } catch(IOException e) { System.out.println("Unable to close file."); }
File Input Example FileReader freader; try { freader = new FileReader("test2.txt"); } catch(IOException e) { System.out.println("Unable to open file."); return; } StreamTokenizer tokenizer = new StreamTokenizer(freader); tokenizer.parseNumbers();
File Input Example try { int type = tokenizer.nextToken(); while(type != StreamTokenizer.TT_EOF) { switch(type) { case StreamTokenizer.TT_WORD: System.out.println(tokenizer.sval); break; case StreamTokenizer.TT_NUMBER: System.out.println(tokenizer.nval); break; } type = tokenizer.nextToken(); } }catch(IOException e) {System.out.println("Error reading file.");} try{ freader.close(); } catch(IOException e) { System.out.println("Unable to close file."); }
File class • java.io.File • Used to refer to files and directories • java.awt.FileDialog • Used to ask the user to choose a file
File Dialog Example Frame frame = new Frame(); frame.show(); FileDialog fd = new FileDialog(frame); fd.show(); String filename = fd.getFile(); String directory = fd.getDirectory(); System.out.println("You chose the file: " + filename); System.out.println("In the directory: " + directory);