java api, exceptions and io
TRANSCRIPT
Java Class Libraries, Exceptions and IO
Jussi PohjolainenTampere University of Applied
Sciences
CLASS LIBRARIES
Class Libraries
• Programming would be very time consuming if everything would be implemented from the beginning.
• Class Libraries: premade classes that the programmer can use.
• Example: You don't implement GUI-elements by yourself, you use the given classes!
• You don't have to understand how the classes have been implemented. You have to understand how to use them!
Java Application Programming Interface
• Documentation available on the Internet– http://java.sun.com/javase/6/docs/api/
• The Java API is divided into– Packages• Contains classes or other packages
– Classes• Contains methods
– Methods
Structure of the Java API
java.io
Math static int round(float a)java.lang
java.applet String
Integer
static double sqrt(double a)
static double sin(double a)
PackagePackage ClassClass MethodsMethods
.
.
.
.
.
.
.
.
.
Importing
• If you want to import all classes from one package:– import java.io.*;
• If you want to import only one class from the package:– import java.io.SomeClass;
• Every Java – app imports automatically the package java.lang.*;
Example: Dateimport java.util.Date;
class App {
public static void main(String [] args) {
Date mydate = new Date();
String now = mydate.toString();
System.out.println(now);
}
}
Example Date - class
• Documentation:– http://java.sun.com/javase/6/docs/api/java/util/D
ate.html
Example: Math.random()// You really don't have to do this, since
// the Math class is in java.lang!
import java.lang.Math;
class App {
public static void main(String [] args) {
double randomValue = Math.random();
System.out.println(randomValue);
}
}
static?
• If method declaration contains static, call the method via Class name:– Class.method();– Math.random();
• If method declaration does NOT contain static, create object and then call object's method– Class object = new Class();– object.method();– Date mydate = new Date();– mydate.toString();
Couple Packages
• Graphical user interface and events:– java.awt– java.awt.event– javax.swing
• Input and output – java.io
• Data Structures, Internationalization, Utility Classes– java.util
Examples
• java.lang.String• java.util.Vector
EXCEPTIONS
Exception Handling
• Exception is a situation where application fail during runtime.
• You can handle these exceptions so you can for example give error messages to user.
Checked vs. Unchecked
• Checked exceptions– You have to implement exception handling– Subclass of Exception
• Unchecked exceptions– You may implement exception handling– Subclass of RuntimeException
• For example: when doing IO you MUST handle exceptions. When handling arrays you MAY handle exceptions
Unchecked Exceptionclass App {
public static void main(String [] args) {
double result = 1/0;
System.out.println(result);
}
}
java AppException in thread "main" java.lang.ArithmeticException: / by zero
at App.main(App.java:3)
Using Exceptionsclass App {
public static void main(String [] args) {
try {
double result = 1/0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("You cannot divide with zero!");
}
}
}
java AppYou cannot divide with zero!
Using Exceptionstry {
// something that can trigger an exception
} catch(ExceptionClass1 e) {
// If it was ExceptionClass1, go here
} catch(ExceptionClass2 e) {
// If it was ExceptionClass2, go here
} finally {
// Do this no matter what
}
Example of Exception Usageclass App {
public static void main(String [] args) {
try {
int a1 = Integer.parseInt(args[0]);
int a2 = Integer.parseInt(args[1]);
double result = a1 / a2;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("You cannot divide with zero!");
} catch (NumberFormatException e) {
System.out.println("Please give integer numbers!");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Please give two integer numbers!");
}
}
}
Integer.parseInt?
• Package: java.lang• Class: Integer• Method: parseInt
It may throw an exception!
NumberFormatException
Inherites RuntimeException=>Unchecked Exception=>You MAY implement exception handling
Exception is the Base Class!class App {
public static void main(String [] args) {
try {
int a1 = Integer.parseInt(args[0]);
int a2 = Integer.parseInt(args[1]);
double result = a1 / a2;
System.out.println(result);
} catch (Exception e) {
System.out.println("Whatever exception is, always come here");
}
}
}
class App { public static void main(String [] args) { try { int a1 = Integer.parseInt(args[0]); int a2 = Integer.parseInt(args[1]); double result = a1 / a2; System.out.println(result); } catch (Exception e) { // Exception is class, e is an object. String errormsg = e.toString(); System.out.println(errormsg); } } }
> java App 4 0java.lang.ArithmeticException: / by zero> java App 4 kjava.lang.NumberFormatException: For input string: "k"> java App 4 java.lang.ArrayIndexOutOfBoundsException: 1
JAVA IO
Input and Output Streams
Input OutputBinary FileInputStream FileOutputStream
Text FileReader FileWriter
Reading Textimport java.io.*;
class App {
public static void main(String [] args) {
try {
// We use int even though characters are read!
int character;
FileReader input = new FileReader("App.java");
// Let's read and print the rest
// input.read() returns -1 when the file is done!
while((character = input.read()) != -1) {
System.out.print( (char) character);
}
// close the stream
input.close();
} catch(IOException e) {
System.out.println("Some problem reading the file");
}
}
}
Writing Textimport java.io.*;
class App {
public static void main(String [] args) {
try {
// We use int even though characters are read!
int character;
FileWriter output = new FileWriter("Test.txt");
do {
// Read from the user one char at a time
character = System.in.read();
// Write the chars to the text file.
// Write until user gives 'q'
output.write(character);
} while( ( (char) character ) != 'q' );
// close the stream
output.close();
} catch(IOException e) {
System.out.println("Some problem reading the file");
}
}
}
Reading and Writing Binaryimport java.io.*;
public class App{ public static void main(String args[]) { int oneByte; try { // For reading FileInputStream input = new FileInputStream("calculator.exe"); // For writing FileOutputStream output = new FileOutputStream("duplicatecalculator.exe"); // Read and write one byte at a time while( (oneByte = input.read()) != -1) { output.write(oneByte); } // close the streams input.close(); output.close(); } catch(IOException e) { System.out.println("Some problem with reading and writing"); } }}
Buffered Stream: BufferedReaderimport java.io.*;
class App { public static void main(String [] args) { try { String line = "something"; FileReader input = new FileReader("App.java"); BufferedReader bf = new BufferedReader(input); while((line = bf.readLine()) != null) { System.out.println(line); } // close the streams bf.close(); input.close(); } catch(IOException e) { System.out.println("Some problem reading the file"); } } }
Buffered Stream: BufferedWriterimport java.io.*;
class App { public static void main(String [] args) { try { FileWriter output = new FileWriter("Test.txt"); BufferedWriter bf = new BufferedWriter(output); bf.write("Hello");
bf.close(); output.close(); } catch(IOException e) { System.out.println("Some problem reading the file"); } } }