User Interfaces File I/O and Exceptions (c) IDMS/SQL News
File I/O Simple Example (c) 2 User Interfaces 4 In Java one can create at least 3 types of programs Windows AppletServlet Java Class A fourth can be applications run from Command Prompt (=DOS)
File I/O Simple Example (c) 3 Different User Interfaces 4 User interface can vary depending upon code execution is at client or server side 4 Here we take the simplest case of File I/O at the client side 4 Programs will be run from the command prompt (=dos window)
File I/O Simple Example (c) 4 I/O - File Based in Java ð We have already seen one form of output – print statement ð System.out.print(“Hello Printer”); ð In reality we are using the print method of the class PrintStream ð System.out is an instance of the class PrintStream ð Note: see tream.html
File I/O Simple Example (c) 5 Output file We can define a file using class called FileOutputStream and PrintStream of package java.io FileOutputStream fout= new FileOutputStream ("Writef1.out"); PrintStream myOutput = new PrintStream(fout); Now one can write to the file “Write1.out” using myOutput.print commands!
File I/O Simple Example (c) 6 import java.io.*; // Class definition and implementation. public class Writef1 { public static void main (String args[]) { try { FileOutputStream fout= new FileOutputStream ("Writef1.out"); PrintStream myOutput = new PrintStream(fout); if (args.length == 0) { myOutput.println("Hello Nobody "); myOutput.println("Try with some arguments ");} else { for (int i=0; i < args.length; i = i+1) { myOutput.println(args[i]);}} } // try ends here catch (IOException e) { System.out.println("Error=" + e); System.exit(1); } // end of catch }
File I/O Simple Example (c) 7 Exceptions try and catch statements Try { code} catch (exception_type xyz1) { code to process this...} There can be multiple catch blocks like our ”call IDMS-STATUS”! When doing file I/O exception must be coded Note: There are other ways to handle exceptions in Java like a method throws....xyzException etc
File I/O Simple Example (c) 8 Exception Example Code class Except1 { public static void main (String args[]) { int i = 0; String [] greetings = { " Merry Christmas", " God Jul ", " Hyvää Joulua"}; try{ for (i=0; i < 4; i = i+1) { System.out.println(greetings[i]);} } // end of try catch (ArrayIndexOutOfBoundsException e ) { System.out.println(" "); System.out.println(" Check Index Variable Value"); System.out.println(" ");} }}