Introduction to Programming in Java Part III: Exception Handling and I/O Marko Boon September 2007
/
department of mathematics and computer science
1/70
Exception Handling public class ExceptionExample1 { public static void main(String[] arg) { int number1 = Integer.parseInt(arg[0]); int number2 = Integer.parseInt(arg[1]); int result = number1 - number2; System.out.print(number1+" - "+number2+" = "); System.out.println(result); } }
/
department of mathematics and computer science
2/70
>java ExceptionExample1 2 4 2 - 4 = -2
>java ExceptionExample1 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at ExceptionExample1.main(ExceptionExample1.java:4)
>java ExceptionExample1 2 5.6 Exception in thread "main" java.lang.NumberFormatException: For input string: "5 .6" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at ExceptionExample1.main(ExceptionExample1.java:5)
/
department of mathematics and computer science
3/70
public class ExceptionExample2 { public static void main(String[] arg) {
} }
/
department of mathematics and computer science
4/70
public class ExceptionExample2 { public static void main(String[] arg) { if (arg.length != 2) System.err.println("Specify 2 arguments."); else {
} } }
/
department of mathematics and computer science
5/70
public class ExceptionExample2 { public static void main(String[] arg) { if (arg.length != 2) System.err.println("Specify 2 arguments."); else { boolean ok = true;
} } }
/
department of mathematics and computer science
6/70
public class ExceptionExample2 { public static void main(String[] arg) { if (arg.length != 2) System.err.println("Specify 2 arguments."); else { boolean ok = true; for (int i = 0; i < 2; i++) {
}
} } }
/
department of mathematics and computer science
7/70
public class ExceptionExample2 { public static void main(String[] arg) { if (arg.length != 2) System.err.println("Specify 2 arguments."); else { boolean ok = true; for (int i = 0; i < 2; i++) { char[] chars = arg[i].toCharArray();
}
} } }
/
department of mathematics and computer science
8/70
public class ExceptionExample2 { public static void main(String[] arg) { if (arg.length != 2) System.err.println("Specify 2 arguments."); else { boolean ok = true; for (int i = 0; i < 2; i++) { char[] chars = arg[i].toCharArray(); for (int j = 0; j < chars.length; j++) if (chars[j] < ’0’ || chars[j] > ’9’) ok = false; }
} } }
/
department of mathematics and computer science
9/70
public class ExceptionExample2 { public static void main(String[] arg) { if (arg.length != 2) System.err.println("Specify 2 arguments."); else { boolean ok = true; for (int i = 0; i < 2; i++) { char[] chars = arg[i].toCharArray(); for (int j = 0; j < chars.length; j++) if (chars[j] < ’0’ || chars[j] > ’9’) ok = false; } if (ok) // parse strings else System.err.println("No integer!"); } } }
/
department of mathematics and computer science
10/70
Exception Handling In Java some methods may ’throw’ an Exception. This means that you have to ’try’ to execute this code. If an exception is thown, you can ’catch’ it and handle it. In the Java documentation you can see whether a certain method throws an Exception or not. One method can throw several kinds of exceptions. You can catch them seperately: try { // method that throws Exceptions } catch (SomeKindOfException e) { // deal with it } catch (OtherKindOfException e) { // deal with it }
/
department of mathematics and computer science
11/70
public class ExceptionExample3 { public static void main(String[] arg) {
} }
/
department of mathematics and computer science
12/70
public class ExceptionExample3 { public static void main(String[] arg) { int number1 = Integer.parseInt(arg[0]); int number2 = Integer.parseInt(arg[1]); int result = number1 - number2; System.out.print(number1+" - "+number2+" = "); System.out.println(result);
} }
/
department of mathematics and computer science
13/70
public class ExceptionExample3 { public static void main(String[] arg) { try { int number1 = Integer.parseInt(arg[0]); int number2 = Integer.parseInt(arg[1]); int result = number1 - number2; System.out.print(number1+" - "+number2+" = "); System.out.println(result); }
} }
/
department of mathematics and computer science
14/70
public class ExceptionExample3 { public static void main(String[] arg) { try { int number1 = Integer.parseInt(arg[0]); int number2 = Integer.parseInt(arg[1]); int result = number1 - number2; System.out.print(number1+" - "+number2+" = "); System.out.println(result); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Specify 2 arguments!"); }
} }
/
department of mathematics and computer science
15/70
public class ExceptionExample3 { public static void main(String[] arg) { try { int number1 = Integer.parseInt(arg[0]); int number2 = Integer.parseInt(arg[1]); int result = number1 - number2; System.out.print(number1+" - "+number2+" = "); System.out.println(result); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Specify 2 arguments!"); } catch (NumberFormatException e) { System.err.println("No integer!"); } } }
/
department of mathematics and computer science
16/70
You can also create and throw your own Exceptions: public class TooYoungException extends Exception { public TooYoungException(String msg) { super(msg); } } Declare that your method might throw an exception: public void show(int age) throws TooYoungException { String err = "Too young to watch Finding Nemo!"; if (age < 18) throw new TooYoungException(err); // show movie } You can use the method getMessage( ) to get the error message.
/
department of mathematics and computer science
17/70
File I/O Package java.io Important classes: 1. File (also for directories) 2. InputStream, Stream
BufferedInputStream,
FileInputStream,
ObjectInput-
3. OutputStream, BufferedOutputStream, FileOutputStream, ObjectOutputStream, PrintStream 4. Reader, BufferedReader, FileReader 5. Writer, BufferedWriter, FileWriter, PrintWriter
/
department of mathematics and computer science
18/70
Reading from plain text files
F ile
/
department of mathematics and computer science
19/70
Reading from plain text files
F ile R e a d e r F ile
/
department of mathematics and computer science
20/70
Reading from plain text files
B u ffe re d R e a d e r F ile R e a d e r F ile
/
department of mathematics and computer science
21/70
Reading from plain text files S trin g [] B u ffe re d R e a d e r F ile R e a d e r F ile
/
department of mathematics and computer science
22/70
Java Implementation public static String[] readFile(String fileName) {
}
/
department of mathematics and computer science
23/70
Java Implementation public static String[] readFile(String fileName) throws IOException {
}
/
department of mathematics and computer science
24/70
Java Implementation public static String[] readFile(String fileName) throws IOException { FileReader fr = new FileReader(fileName);
}
/
department of mathematics and computer science
25/70
Java Implementation public static String[] readFile(String fileName) throws IOException { FileReader fr = new FileReader(fileName); BufferedReader reader = new BufferedReader(fr);
}
/
department of mathematics and computer science
26/70
Java Implementation public static String[] readFile(String fileName) throws IOException { FileReader fr = new FileReader(fileName); BufferedReader reader = new BufferedReader(fr); Vector lines = new Vector();
}
/
department of mathematics and computer science
27/70
Java Implementation public static String[] readFile(String fileName) throws IOException { FileReader fr = new FileReader(fileName); BufferedReader reader = new BufferedReader(fr); Vector lines = new Vector(); while (reader.ready()) {
}
}
/
department of mathematics and computer science
28/70
Java Implementation public static String[] readFile(String fileName) throws IOException { FileReader fr = new FileReader(fileName); BufferedReader reader = new BufferedReader(fr); Vector lines = new Vector(); while (reader.ready()) { String s = reader.readLine(); }
}
/
department of mathematics and computer science
29/70
Java Implementation public static String[] readFile(String fileName) throws IOException { FileReader fr = new FileReader(fileName); BufferedReader reader = new BufferedReader(fr); Vector lines = new Vector(); while (reader.ready()) { String s = reader.readLine(); lines.addElement(s); }
}
/
department of mathematics and computer science
30/70
Java Implementation public static String[] readFile(String fileName) throws IOException { FileReader fr = new FileReader(fileName); BufferedReader reader = new BufferedReader(fr); Vector lines = new Vector(); while (reader.ready()) { String s = reader.readLine(); lines.addElement(s); } reader.close();
}
/
department of mathematics and computer science
31/70
Java Implementation public static String[] readFile(String fileName) throws IOException { FileReader fr = new FileReader(fileName); BufferedReader reader = new BufferedReader(fr); Vector lines = new Vector(); while (reader.ready()) { String s = reader.readLine(); lines.addElement(s); } reader.close(); String[] strLines = new String[lines.size()];
}
/
department of mathematics and computer science
32/70
Java Implementation public static String[] readFile(String fileName) throws IOException { FileReader fr = new FileReader(fileName); BufferedReader reader = new BufferedReader(fr); Vector lines = new Vector(); while (reader.ready()) { String s = reader.readLine(); lines.addElement(s); } reader.close(); String[] strLines = new String[lines.size()]; lines.copyInto(strLines); }
/
department of mathematics and computer science
33/70
Java Implementation public static String[] readFile(String fileName) throws IOException { FileReader fr = new FileReader(fileName); BufferedReader reader = new BufferedReader(fr); Vector lines = new Vector(); while (reader.ready()) { String s = reader.readLine(); lines.addElement(s); } reader.close(); String[] strLines = new String[lines.size()]; lines.copyInto(strLines); return strLines; }
/
department of mathematics and computer science
34/70
Writing to plain text files S trin g
/
department of mathematics and computer science
35/70
Writing to plain text files S trin g P rin tW rite r
/
department of mathematics and computer science
36/70
Writing to plain text files S trin g P rin tW rite r F ile W rite r
/
department of mathematics and computer science
37/70
Writing to plain text files S trin g P rin tW rite r F ile W rite r F ile
/
department of mathematics and computer science
38/70
Java Implementation public static void writeFile(String fileName, String[] lines) {
}
/
department of mathematics and computer science
39/70
Java Implementation public static void writeFile(String fileName, String[] lines) throws IOException {
}
/
department of mathematics and computer science
40/70
Java Implementation public static void writeFile(String fileName, String[] lines) throws IOException { FileWriter fw = new FileWriter(fileName);
}
/
department of mathematics and computer science
41/70
Java Implementation public static void writeFile(String fileName, String[] lines) throws IOException { FileWriter fw = new FileWriter(fileName); PrintWriter writer = new PrintWriter(fw);
}
/
department of mathematics and computer science
42/70
Java Implementation public static void writeFile(String fileName, String[] lines) throws IOException { FileWriter fw = new FileWriter(fileName); PrintWriter writer = new PrintWriter(fw); for (int i = 0; i < lines.length; i++) writer.println(lines[i]);
}
/
department of mathematics and computer science
43/70
Java Implementation public static void writeFile(String fileName, String[] lines) throws IOException { FileWriter fw = new FileWriter(fileName); PrintWriter writer = new PrintWriter(fw); for (int i = 0; i < lines.length; i++) writer.println(lines[i]); writer.flush(); }
/
department of mathematics and computer science
44/70
Java Implementation public static void writeFile(String fileName, String[] lines) throws IOException { FileWriter fw = new FileWriter(fileName); PrintWriter writer = new PrintWriter(fw); for (int i = 0; i < lines.length; i++) writer.println(lines[i]); writer.flush(); writer.close(); }
/
department of mathematics and computer science
45/70
I/O Exception Handling public static void main(String[] arg) {
}
/
department of mathematics and computer science
46/70
I/O Exception Handling public static void main(String[] arg) { String[] lines = readFile(arg[0]);
}
/
department of mathematics and computer science
47/70
I/O Exception Handling public static void main(String[] arg) { String[] lines = readFile(arg[0]); writeFile(arg[1], lines);
}
/
department of mathematics and computer science
48/70
I/O Exception Handling public static void main(String[] arg) { try { String[] lines = readFile(arg[0]); writeFile(arg[1], lines); }
}
/
department of mathematics and computer science
49/70
I/O Exception Handling public static void main(String[] arg) { try { String[] lines = readFile(arg[0]); writeFile(arg[1], lines); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Specify two filenames."); }
}
/
department of mathematics and computer science
50/70
I/O Exception Handling public static void main(String[] arg) { try { String[] lines = readFile(arg[0]); writeFile(arg[1], lines); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Specify two filenames."); } catch (FileNotFoundException e) { System.err.println("File not found."); }
}
/
department of mathematics and computer science
51/70
I/O Exception Handling public static void main(String[] arg) { try { String[] lines = readFile(arg[0]); writeFile(arg[1], lines); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Specify two filenames."); } catch (FileNotFoundException e) { System.err.println("File not found."); } catch (IOException e) { System.err.println("Unknown error."); } }
/
department of mathematics and computer science
52/70
1.
Packages and CLASSPATH
CLASSPATH A system environment variable that contains one or more directories. The Java compiler will only find source files located in directories that are part of the CLASSPATH. −→ make sure that the current directory (.) is in your CLASSPATH! Is is also recommended to add the root directory of your project to the CLASSPATH. Packages
Collection of classes that somehow belong together. The sources of these classes should be stored in a directory with the same name as the package. Importing classes from another package is possible using the full name (e.g. java.io.File) or importing the package (e.g. import java.io.* or import java.io.File).
/
department of mathematics and computer science
53/70
Compiling and running Java files Not part of package javac MainFile.java java MainFile Part of package javac package\MainFile.java java package.MainFile
/
department of mathematics and computer science
54/70
2.
Creating an Executable Program
1. Create a JAR file. This file can be executed on any system with the Java Runtime Environment installed by double-clicking on it. 2. Create an installation CD-ROM.
/
department of mathematics and computer science
55/70
Step 1: create a JAR file Create a file in project root directory, called manifest.mf: Manifest-Version: 1.0 Main-Class: GUITest Created-By: Your name If your project loads classes from an external jar file (e.g. from the JExcel jar file jxl.jar), you need to add another line that adds this jar file to the CLASSPATH (multiple jar files should be delimited by a space character): Class-Path: jxl.jar
/
department of mathematics and computer science
56/70
Step 1: create a JAR file Usage: -c -t -x -u -v -f -m
jar ctxu[vfm] [jar-file] [manifest-file] files create new archive list table of contents for archive extract named (or all) files from archive update existing archive generate verbose output on standard output specify archive file name include manifest information from specified manifest file
/
department of mathematics and computer science
57/70
Random Number Generator Main class: GUITest.java Packages: data, gui, math, statistics, tools Nested packages (like tools.chart) do not have to be called separately. The command line becomes: jar -cfm rng.jar manifest.mf data gui math statistics tools images GUITest.* jar -i rng.jar
/
department of mathematics and computer science
58/70
Step 2: create the directory structure
• download self-extracting compressed zip file installcd.exe. • Unzip this file to a suitable location (e.g. in your project directory). It will create a directory called installcd, containing the files setup.exe, autorun.inf and settings.ini (and a required DLL file). It also contains a subdirectory called program which contains the files program.exe and the same DLL file.
• Copy the JAR file to this program directory. • Copy all non-class files that belong to the project (external program, JPG or GIF images) used in your program. Use the same directory structure!
/
department of mathematics and computer science
59/70
Step 3: set the program name • Open installcd\settings.ini in a text editor
/
department of mathematics and computer science
60/70
Step 3: set the program name • Open installcd\settings.ini in a text editor
[Main] ProgName= ProgDir= JarExeName=
/
department of mathematics and computer science
61/70
Step 3: set the program name • Open installcd\settings.ini in a text editor • add a program name to the second line (spaces allowed, no quotes)
[Main] ProgName= ProgDir= JarExeName=
/
department of mathematics and computer science
62/70
Step 3: set the program name • Open installcd\settings.ini in a text editor • add a program name to the second line (spaces allowed, no quotes)
[Main] ProgName=Random Number Generator ProgDir= JarExeName=
/
department of mathematics and computer science
63/70
Step 3: set the program name • Open installcd\settings.ini in a text editor • add a program name to the second line (spaces allowed, no quotes) • add a default installation directory name
[Main] ProgName=Random Number Generator ProgDir= JarExeName=
/
department of mathematics and computer science
64/70
Step 3: set the program name • Open installcd\settings.ini in a text editor • add a program name to the second line (spaces allowed, no quotes) • add a default installation directory name
[Main] ProgName=Random Number Generator ProgDir=rng JarExeName=
/
department of mathematics and computer science
65/70
Step 3: set the program name • Open installcd\settings.ini in a text editor • add a program name to the second line (spaces allowed, no quotes) • add a default installation directory name • add the name of the main Jar file
[Main] ProgName=Random Number Generator ProgDir=rng JarExeName=
/
department of mathematics and computer science
66/70
Step 3: set the program name • Open installcd\settings.ini in a text editor • add a program name to the second line (spaces allowed, no quotes) • add a default installation directory name • add the name of the main Jar file
[Main] ProgName=Random Number Generator ProgDir=rng JarExeName=rng
/
department of mathematics and computer science
67/70
Step 4: add an icon (optional)
• create an icon file • give it the same name as your JAR file (of course replace .jar by .ico)
• put it into the installcd\program directory. Shareware program to create icons:
• IconXP (www.aha-soft.com) • MicroAngelo (www.impactsoftware.com)
/
department of mathematics and computer science
68/70
Step 5: add the Java Runtime Environment Add the installation program for the Java Runtime Environment to the installcd directory.
• download the latest version from http://java.sun.com/j2se • place the downloaded file in the installcd directory • rename it to jre.exe.
/
department of mathematics and computer science
69/70
Step 6: test and burn the CD-ROM
• run setup.exe to test the installation from your harddisk • if possible, test it on other computers without Java in your network by mapping your drive
• burn the CD-ROM. The installcd directory should be the root of the CDROM, otherwise the autorun program will not work.
• test the installation program again
/
department of mathematics and computer science
70/70