Java as a Second Language

User Interfaces
File I/O and Exceptions
(c) IDMS/SQL News
http://www.geocities.com/idmssql
User Interfaces
 In Java one can create at least 3 types of
programs
Windows
Applet
Servlet
Java Class
A fourth can be applications run from Command Prompt (=DOS)
File I/O Simple Example
(c)http://www.geocities.com/idmssql
2
Different User Interfaces
 User interface can vary depending upon
code execution is at client or server side
 Here we take the simplest case of File I/O at
the client side
 Programs will be run from the command
prompt (=dos window)
File I/O Simple Example
(c)http://www.geocities.com/idmssql
3
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
http://java.sun.com/j2se/1.3/docs/api/java/io/PrintS
tream.html
File I/O Simple Example
(c)http://www.geocities.com/idmssql
4
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)http://www.geocities.com/idmssql
5
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)http://www.geocities.com/idmssql
6
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)http://www.geocities.com/idmssql
7
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(" --------------------------");}
}}
File I/O Simple Example
(c)http://www.geocities.com/idmssql
8