Lecture 7: I/O, Threads, Exceptions, Debugging

What You Will Learn Today

  1. Manage input and output using streams and command-line arguments.
  2. Write to and read from object streams using serialization.
  3. Create and manage multiple threads within a program.
  4. Throw and handle exceptions.
  5. Use testing and debugging methods and tools including trace messages and debuggers.

Streams

Categories of Streams

File Streams

FileReader reader = new FileReader("input.txt"); // text characters
FileInputStream inputStream = new FileInputStream("input.dat"); // binary bytes
FileWriter writer = new FileWriter("output.txt"); // text characters
FileOutputStream outputStream = new FileOutputStream("output.dat"); // binary bytes

Streams for Text Files

BufferedReader in = new BufferedReader(reader);
String inputLine = in.readLine();
// returns null if end of file is reached: no more lines to read
PrintWriter
out = new PrintWriter(writer);
out.println("Hello, World!");

Standard I/O

Keyboard Class

The Keyboard class is not part of the Java standard library, but we use it because it hides I/O details for beginners:

Command-Line Arguments

Object Streams

MyClass myObject = ...;
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("myfile.dat"));
out.writeObject(myObject);
ObjectInputStream in = new ObjectInputStream(new FileInputStream("myfile.dat"));
MyClass myObject = (MyClass) in.readObject();

Object Serialization

Threads

Exceptions

Using Exceptions

Testing

Debugging Methods

Trace Messages and Assertions

Debuggers

Debugger Essentials

Java Debugger

To Do After Class