KEMBAR78
Java API, Exceptions and IO | PPT
Java Class Libraries, Exceptions and IO Jussi Pohjolainen Tampere 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) Package Class Methods . . . . . . . . .
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: Date import 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/Date.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 Exception class App { public static void main(String [] args) { double result = 1/0; System.out.println(result); }  } java App Exception in thread "main" java.lang.ArithmeticException: / by zero at App.main(App.java:3)
Using Exceptions class 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 App You cannot divide with zero!
Using Exceptions try { // 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 Usage 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 (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 0 java.lang.ArithmeticException: / by zero > java App 4 k java.lang.NumberFormatException: For input string: "k" > java App 4  java.lang.ArrayIndexOutOfBoundsException: 1
JAVA IO
Input and Output Streams Input Output Binary FileInputStream FileOutputStream Text FileReader FileWriter
Reading Text import 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 Text import 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 Binary import 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: BufferedReader import 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: BufferedWriter import 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"); } }  }

Java API, Exceptions and IO

  • 1.
    Java Class Libraries,Exceptions and IO Jussi Pohjolainen Tampere University of Applied Sciences
  • 2.
  • 3.
    Class Libraries Programmingwould 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!
  • 4.
    Java Application ProgrammingInterface 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
  • 5.
    Structure of theJava 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) Package Class Methods . . . . . . . . .
  • 6.
    Importing If youwant 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.*;
  • 7.
    Example: Date importjava.util.Date; class App { public static void main(String [] args) { Date mydate = new Date(); String now = mydate.toString(); System.out.println(now); } }
  • 8.
    Example Date -class Documentation: http://java.sun.com/javase/6/docs/api/java/util/Date.html
  • 9.
    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); } }
  • 10.
    static? If methoddeclaration 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();
  • 11.
  • 12.
  • 13.
    Couple Packages Graphicaluser interface and events: java.awt java.awt.event javax.swing Input and output java.io Data Structures, Internationalization, Utility Classes java.util
  • 14.
  • 15.
  • 16.
    Exception Handling Exceptionis a situation where application fail during runtime. You can handle these exceptions so you can for example give error messages to user.
  • 17.
    Checked vs. UncheckedChecked 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
  • 18.
    Unchecked Exception classApp { public static void main(String [] args) { double result = 1/0; System.out.println(result); } } java App Exception in thread "main" java.lang.ArithmeticException: / by zero at App.main(App.java:3)
  • 19.
    Using Exceptions classApp { 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 App You cannot divide with zero!
  • 20.
    Using Exceptions try{ // 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 }
  • 21.
    Example of ExceptionUsage 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 (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!"); } } }
  • 22.
    Integer.parseInt? Package: java.langClass: Integer Method: parseInt It may throw an exception!
  • 23.
    NumberFormatException Inherites RuntimeException=>Unchecked Exception =>You MAY implement exception handling
  • 24.
    Exception is theBase 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"); } } }
  • 25.
    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 0 java.lang.ArithmeticException: / by zero > java App 4 k java.lang.NumberFormatException: For input string: "k" > java App 4 java.lang.ArrayIndexOutOfBoundsException: 1
  • 26.
  • 27.
    Input and OutputStreams Input Output Binary FileInputStream FileOutputStream Text FileReader FileWriter
  • 28.
    Reading Text importjava.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"); } } }
  • 29.
    Writing Text importjava.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"); } } }
  • 30.
    Reading and WritingBinary import 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"); } } }
  • 31.
    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"); } } }
  • 32.
    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"); } } }

Editor's Notes