essential java classes mainly classes in the java.lang and java.io packages

92
Essential Java classes mainly classes in the java.lang and java.io packages

Upload: della-francis

Post on 31-Dec-2015

262 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Essential Java classes mainly classes in the java.lang and java.io packages

Essential Java classes

mainly classes in the java.lang and java.io packages

Page 2: Essential Java classes mainly classes in the java.lang and java.io packages

Contents

• Handling errors using exceptions

• Multi-threading

• I/O

• Setting program attributes

• Accessing system resources

Page 3: Essential Java classes mainly classes in the java.lang and java.io packages

Exceptions

• The Java programming language uses exceptions to provide error-handling capabilities for its programs

• An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions

• When an error occurs within a method, the method creates an object and hands it off to the runtime system

• The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred

• Creating an exception object and handing it to the runtime system is called throwing an exception

Page 4: Essential Java classes mainly classes in the java.lang and java.io packages

Exception handling

Page 5: Essential Java classes mainly classes in the java.lang and java.io packages

• //Note: This class won't compile by design! import java.io.*; import java.util.Vector; public class ListOfNumbers {

private Vector victor; private static final int SIZE = 10; public ListOfNumbers () {

victor = new Vector(SIZE); for (int i = 0; i < SIZE; i++) {

victor.addElement(new Integer(i)); } } public void writeList() {

PrintWriter out = new PrintWriter( new

FileWriter("OutFile.txt")); for (int i = 0; i < SIZE; i++) {

out.println("Value at: " + i + " = " + victor.elementAt(i)); }

out.close(); } }

Page 6: Essential Java classes mainly classes in the java.lang and java.io packages

• private Vector victor; private static final int SIZE = 10; PrintWriter out = null; try {

System.out.println("Entered try statement"); out = new PrintWriter(new

FileWriter("OutFile.txt")); for (int i = 0; i < SIZE; i++) {

out.println("Value at: " + i + " = " + victor.elementAt(i));

} }

catch and finally statements . . .

Page 7: Essential Java classes mainly classes in the java.lang and java.io packages

Catch exceptions

• try { } catch (FileNotFoundException e) {

System.err.println("FileNotFoundException: " + e.getMessage());

throw new SampleException(e); } catch (IOException e) {

System.err.println("Caught IOException: " + e.getMessage());

}

Page 8: Essential Java classes mainly classes in the java.lang and java.io packages

Finally

• finally { if (out != null) {

System.out.println("Closing PrintWriter");

out.close(); } else {

System.out.println("PrintWriter not open");

} }

Page 9: Essential Java classes mainly classes in the java.lang and java.io packages

Specify exceptions thrown by methods

• public void writeList() throws IOException { PrintWriter out = new PrintWriter(

new FileWriter("OutFile.txt")); for (int i = 0; i < SIZE; i++) {

out.println("Value at: " + i + " = " + victor.elementAt(i));

} out.close();

}

Page 10: Essential Java classes mainly classes in the java.lang and java.io packages

Throw exceptions

• public Object pop() throws EmptyStackException {

Object obj; if (size == 0) { throw new EmptyStackException(); } obj = objectAt(SIZE - 1); setObjectAt(SIZE - 1, null); size--; return obj;

}

Page 11: Essential Java classes mainly classes in the java.lang and java.io packages

Exception classes

Page 12: Essential Java classes mainly classes in the java.lang and java.io packages

Chained exceptions

• Relevant constructor and methods– Throwable getCause() – Throwable initCause(Throwable) – Throwable(String, Throwable) – Throwable(Throwable)

• try { } catch (IOException e) {

throw new SampleException("Other IOException", e); }

Page 13: Essential Java classes mainly classes in the java.lang and java.io packages

Accessing stack trace

• catch (Exception cause) { StackTraceElement elements[] =

cause.getStackTrace(); for (int i = 0, n = elements.length; i < n; i+

+) {

System.err.println(elements[i].getFileName() + ":" + elements[i].getLineNumber() + ">> " + elements[i].getMethodName() + "()");

} }

Page 14: Essential Java classes mainly classes in the java.lang and java.io packages

Logging API

• try { Handler handler = new FileHandler("OutFile.log"); Logger.getLogger("").addHandler(handler); } catch (IOException e) { Logger logger = Logger.getLogger("package.name"); StackTraceElement elements[] = e.getStackTrace(); for (int i = 0; n = elements.length; i < n; i++) { logger.log(Level.WARNING, elements[i].getMethodName()); } }

Page 15: Essential Java classes mainly classes in the java.lang and java.io packages

Contents

• Handling errors using exceptions

• Multi-threading

• I/O

• Setting program attributes

• Accessing system resources

Page 16: Essential Java classes mainly classes in the java.lang and java.io packages

Thread • A thread — sometimes called an execution context

or a lightweight process — is a single sequential flow of control within a program

• A thread is similar to a real process in that both have a single sequential flow of control. However, a thread is considered lightweight because it runs within the context of a full-blown program and takes advantage of the resources allocated for that program

• As a sequential flow of control, a thread must carve out some resources within a running program. For example, a thread must have its own execution stack and program counter

Page 17: Essential Java classes mainly classes in the java.lang and java.io packages

A timer• import java.util.Timer; // Simple demo that uses

java.util.Timer to // schedule a task to execute once 5 seconds have

passedimport java.util.TimerTask; public class Reminder {

Timer timer; public Reminder(int seconds) {

timer = new Timer(); timer.schedule(new RemindTask(),

seconds*1000); } class RemindTask extends TimerTask { public void run() { System.out.format("Time's up!%n"); timer.cancel(); //Terminate the timer thread } }

public static void main(String args[]) { new Reminder(5); System.out.format("Task scheduled.%n"); } }

Page 18: Essential Java classes mainly classes in the java.lang and java.io packages

Steps of implementing timer• Implement a custom subclass of TimerTask. The

run method contains the code that performs the task.

• Create a thread by instantiating the Timer class. • Instantiate the TimerTask object. • Schedule the timer task for execution.• //Get the Date corresponding to 11:01:00 pm today.

Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 1); calendar.set(Calendar.SECOND, 0); Date time = calendar.getTime(); timer = new Timer(); timer.schedule(new RemindTask(), time);

Page 19: Essential Java classes mainly classes in the java.lang and java.io packages

Stopping timer thread• Invoke cancel on the timer. You can do this from

anywhere in the program, such as from a timer task's run method.

• Make the timer's thread a "daemon" by creating the timer like this: new Timer(true). If the only threads left in the program are daemon threads, the program exits.

• After all the timer's scheduled tasks have finished executing, remove all references to the Timer object. Eventually, the timer's thread will terminate.

• Invoke the System.exit method, which makes the entire program (and all its threads) exit.

Page 20: Essential Java classes mainly classes in the java.lang and java.io packages

• public class ReminderBeep { ... public ReminderBeep(int seconds) {

toolkit = Toolkit.getDefaultToolkit(); timer = new Timer(); timer.schedule(new RemindTask(),

seconds*1000); } class RemindTask extends TimerTask { public void run() {

System.out.format("Time's up!%n"); toolkit.beep(); //timer.cancel(); //Not necessary

because //we call System.exit.

System.exit(0); //Stops the AWT thread //(and everything else).

} } ... }

Page 21: Essential Java classes mainly classes in the java.lang and java.io packages

Periodic task• public class AnnoyingBeep {

Toolkit toolkit; Timer timer; public AnnoyingBeep() {

toolkit = Toolkit.getDefaultToolkit(); timer = new Timer(); timer.schedule(new RemindTask(),

0, //initial delay 1*1000); //subsequent rate

} class RemindTask extends TimerTask {

int numWarningBeeps = 3; public void run() {

if (numWarningBeeps > 0) {toolkit.beep();

numWarningBeeps--; } System.exit(0); } } }

Page 22: Essential Java classes mainly classes in the java.lang and java.io packages

Implementing a thread• Subclassing Thread class and overriding run method• public class SimpleThread extends Thread {

public SimpleThread(String str) { super(str);

} public void run() {

for (int i = 0; i < 10; i++) { System.out.format("%d %s%n", i,

getName()); try {

sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) {}

} System.out.format("DONE! %s%n", getName());

} }

Page 23: Essential Java classes mainly classes in the java.lang and java.io packages

• public class TwoThreadsTest { public static void main (String[] args) {

new SimpleThread("Jamaica").start();

new SimpleThread("Fiji").start(); }

}

Page 24: Essential Java classes mainly classes in the java.lang and java.io packages

• Implement the Runnable interface and its run method and then create a thread with itself as the Thread's target.

• public class Clock extends java.applet.Applet implements Runnable { private volatile Thread clockThread = null; public void start() { if (clockThread == null) { clockThread = new Thread(this, "Clock"); clockThread.start(); } } public void run() { Thread myThread = Thread.currentThread(); while (clockThread == myThread) { repaint(); try { Thread.sleep(1000); } catch (InterruptedException e){ } } } public void stop() { clockThread = null; }

Page 25: Essential Java classes mainly classes in the java.lang and java.io packages

Life cycle of a thread

Page 26: Essential Java classes mainly classes in the java.lang and java.io packages

Life cycle of a thread• A thread is started by its start() method• A thread enters Not Runnable state when one of the

following events occurs: – Its sleep method is invoked. – The thread calls the wait method to wait for a specific condition

to be satisifed. – The thread is blocking on I/O

• A thread should arrange for its own death by having a run method that terminates naturally

• Thread.getState() method returns Thread.State values that include: NEW, RUNNABLE, BLOCKED , WAITING, TIMED_WAITING, TERMINATED

• The Thread.isAlive() method returns true if the thread has been started and not stopped

Page 27: Essential Java classes mainly classes in the java.lang and java.io packages

Scheduling • The Java runtime environment supports a very

simple, deterministic algorithm called fixed-priority scheduling

• This algorithm schedules threads on the basis of their priority relative to other Runnable threads

• When a thread is created, it inherits its priority from the thread that created it.

• In addition, by using the setPriority method, you can modify a thread's priority at any time after its creation.

• Thread priorities are integers that range between MIN_PRIORITY and MAX_PRIORITY (constants defined in the Thread class).

Page 28: Essential Java classes mainly classes in the java.lang and java.io packages

Relinquishing the CPU

• Writing CPU-intensive code can have negative repercussions on other threads running in the same process.

• In general, try to write well-behaved threads that voluntarily relinquish the CPU periodically and give other threads an opportunity to run.

• A thread can voluntarily yield the CPU by calling the yield method, which gives other threads of the same priority a chance to run. If no equal-priority threads are Runnable, yield is ignored.

Page 29: Essential Java classes mainly classes in the java.lang and java.io packages

Synchronizing threads• public class Producer extends Thread {

private CubbyHole cubbyhole; private int number; public Producer(CubbyHole c, int number) {

cubbyhole = c; this.number = number;

} public void run() {

for (int i = 0; i < 10; i++) { cubbyhole.put(number, i); try {

sleep((int)(Math.random() * 100)); } catch (InterruptedException e) { } } }

}

Page 30: Essential Java classes mainly classes in the java.lang and java.io packages

• public class Consumer extends Thread {private CubbyHole cubbyhole; private int number; public Consumer(CubbyHole c, int number) {

cubbyhole = c; this.number = number;

} public void run() {

int value = 0; for (int i = 0; i < 10; i++) {

value = cubbyhole.get(number); }

} }

Page 31: Essential Java classes mainly classes in the java.lang and java.io packages

Locking an object

• public class CubbyHole { private int contents; private boolean available = false; public synchronized int get(int who) { //CubbyHole locked by the Producer. ... //CubbyHole unlocked by the Producer } public synchronized void put(int who, int

value) {//CubbyHole locked by the Consumer. ... //CubbyHole unlocked by the Consumer. }

Page 32: Essential Java classes mainly classes in the java.lang and java.io packages

Reentrant lock

• The same thread can call a synchronized method on an object for which it already holds the lock, thereby reacquiring the lock

• The Java runtime environment allows a thread to reacquire a lock because the locks are reentrant

• Reentrant locks are important because they eliminate the possibility of a single thread having to wait for a lock that it already holds

Page 33: Essential Java classes mainly classes in the java.lang and java.io packages

notify and wait methods

• public synchronized int get() { //Won't work!if (available == true) {

available = false; return contents; }

} public synchronized void put(int value) { //Won't work!

if (available == false) { available = true; contents = value; }

}

Page 34: Essential Java classes mainly classes in the java.lang and java.io packages

• public synchronized int get() { while (available == false) {

try { //Wait for Producer to put value. wait();

} catch (InterruptedException e) { } } available = false; notifyAll(); //Notify Producer that value has been

retrieved. return contents;

} public synchronized void put(int value) {

while (available == true) { try { //Wait for Consumer to get value.

wait(); } catch (InterruptedException e) { } }

contents = value; available = true;. notifyAll(); //Notify Consumer that value has

been set}

Page 35: Essential Java classes mainly classes in the java.lang and java.io packages

Running the consumer/producer

• public class ProducerConsumerTest { public static void main(String[] args) {

CubbyHole c = new CubbyHole(); Producer p = new Producer(c, 1); Consumer c = new Consumer(c, 1); p.start(); c.start();

} }

Page 36: Essential Java classes mainly classes in the java.lang and java.io packages

Explicit lock• An explicit lock is more flexible than using the

synchronized keyword because the lock can span a few statements in a method or multiple methods in addition to the scopes (block and method) supported by synchronized

• To create an explicit lock, instantiate an implementation of the Lock interface, usually ReentrantLock. To grab the lock, invoke the lock method; to release the lock, invoke the unlock method. You should wrap the lock and unlock methods in a try/finally clause

• To wait on an explicit lock, create a condition variable (an object that supports the Condition interface) using the Lock.newCondition method. Condition variables provide the methods await — to wait for the condition to be true, and signal and signalAll — to notify all waiting threads that the condition has occurred

Page 37: Essential Java classes mainly classes in the java.lang and java.io packages

• import java.util.concurrent.locks.*; public class CubbyHole2 {

private int contents; private boolean available = false; private Lock aLock = new ReentrantLock(); private Condition condVar =

aLock.newCondition(); public int get(int who) {

aLock.lock(); try { while (available == false) {

try { condVar.await(); } catch (InterruptedException e) { }

} available = false;

condVar.signalAll(); } finally { aLock.unlock(); } return contents;

}

Page 38: Essential Java classes mainly classes in the java.lang and java.io packages

public void put(int who, int value) { aLock.lock(); try {

while (available == true) { try { condVar.await(); } catch (InterruptedException e) { }

} contents = value; available = true; System.out.format("Producer %d put: %d

%n", who, contents);

condVar.signalAll(); } finally { aLock.unlock(); }

}

Page 39: Essential Java classes mainly classes in the java.lang and java.io packages

Synchronized data structure

• In your programs, you probably will want to take advantage of the java.util.concurrent package's data structures that hide all the synchronization details

Page 40: Essential Java classes mainly classes in the java.lang and java.io packages

• import java.util.concurrent.*; public class Producer3 extends Thread {

private BlockingQueue cubbyhole; private int number; public Producer3(BlockingQueue c, int num) {

cubbyhole = c; number = num;

} public void run() { for (int i = 0; i < 10; i++) {

try { cubbyhole.put(i); System.out.format("Producer #%d put:

%d%n", number, i);

sleep((int)(Math.random() * 100)); } catch (InterruptedException e) { } }

} }

Page 41: Essential Java classes mainly classes in the java.lang and java.io packages

• import java.util.concurrent.*; public class ProducerConsumerTest3 {

public static void main(String[] args) { ArrayBlockingQueue c = new

ArrayBlockingQueue(1); Producer3 p = new Producer3(c, 1); Consumer3 c = new Consumer3(c, 1); p.start(); c.start();

} }

Page 42: Essential Java classes mainly classes in the java.lang and java.io packages

Thread pool• A thread pool is a managed collection of threads

that are available to perform tasks. Thread pools usually provide the following: – Improved performance when executing large numbers of

tasks as a result of reduced per-task invocation overhead. – A way of bounding the resources, including threads,

consumed when executing a collection of tasks

• In addition, thread pools relieve you from having to manage the life cycle of threads.

• They allow to take advantage of threading, but focus on the tasks that you want the threads to perform instead of thread mechanics

Page 43: Essential Java classes mainly classes in the java.lang and java.io packages

Thread pool• To use thread pools, instantiate an implementation of the

ExecutorService interface and hand it a set of tasks.

• The choices of configurable thread pool implementations are ThreadPoolExecutor and ScheduledThreadPoolExecutor.

• Recommend using the more convenient factory methods of the Executors class listed in the following table.

Factory Methods in the Executors Class

newFixedThreadPool(int) Creates a fixed-size thread pool.

newCachedThreadPool Creates an unbounded thread pool

with automatic thread reclamation.

newSingleThreadExecutorCreates a single background thread.

Page 44: Essential Java classes mainly classes in the java.lang and java.io packages

• public class WorkerThread implements Runnable { private int workerNumber; WorkerThread(int number) {

workerNumber = number; } public void run() {

for (int i=0;i<=100;i+=20) { //Perform some work...

System.out.format("Worker number: %d, percent complete: %d%n", workerNumber, i);

try { Thread.sleep((int)(Math.random() * 1000));

} catch (InterruptedException e) { } }

} }

Page 45: Essential Java classes mainly classes in the java.lang and java.io packages

• import java.util.concurrent.*; public class ThreadPoolTest {

public static void main(String[ ] args) { int numWorkers = Integer.parseInt(args[0]); int threadPoolSize =

Integer.parseInt(args[1]); ExecutorService tpes = Executors.newFixedThreadPool

(threadPoolSize); WorkerThread[ ] workers =

new WorkerThread[numWorkers]; for (int i = 0; i < numWorkers; i++) {

workers[i] = new WorkerThread(i); tpes.execute(workers[i]);

} tpes.shutdown();

} }

Page 46: Essential Java classes mainly classes in the java.lang and java.io packages

• import java.util.concurrent.*; public class CallableWorkerThread implements Callable<Integer> { private int workerNumber; CallableWorkerThread(int number) {

workerNumber = number; } public Integer call() {

for (int i = 0; i <= 100; i += 20) { //Perform some work...

System.out.format("Worker number: %d, percent complete: %d%n", workerNumber,

i); try {

Thread.sleep((int)(Math.random() * 1000)); } catch (InterruptedException e) {}

} return(workerNumber); } }

Page 47: Essential Java classes mainly classes in the java.lang and java.io packages

• public class ThreadPoolTest2 { public static void main(String[] args) {

int numWorkers = Integer.parseInt(args[0]); ExecutorService tpes =

Executors.newCachedThreadPool(); CallableWorkerThread workers[] = new

CallableWorkerThread[numWorkers]; Future<Integer> futures[] = new

Future[numWorkers]; for (int i = 0; i < numWorkers; i++) {

workers[i] = new CallableWorkerThread(i);

futures[i]=tpes.submit(workers[i]); } for (int i = 0; i < numWorkers; i++) {

try { System.out.format("Ending worker:

%d%n", futures[i].get()); } catch (Exception e) {} }

} }

Page 48: Essential Java classes mainly classes in the java.lang and java.io packages

Contents

• Handling errors using exceptions

• Multi-threading

• I/O

• Setting program attributes

• Accessing system resources

Page 49: Essential Java classes mainly classes in the java.lang and java.io packages

I/O streams

Page 50: Essential Java classes mainly classes in the java.lang and java.io packages

I/O algorithms

Reading Writing

1. open a stream 2. while more

information read information

3. close the stream

1. open a stream 2. while more

information write information

3. close the stream

Page 51: Essential Java classes mainly classes in the java.lang and java.io packages

Class hierarchies in java.io

• The java.io package contains two independent hierarchies of classes: – one for reading / writing bytes – the other for reading / writing characters.

Page 52: Essential Java classes mainly classes in the java.lang and java.io packages

Character Streams• Subclasses of Reader and Writer has two categories:

– those that read from or write to data sinks and – those that perform some sort of processing

Page 53: Essential Java classes mainly classes in the java.lang and java.io packages

Character Streams• Subclasses of Reader and Writer has two categories:

– those that read from or write to data sinks and – those that perform some sort of processing

Page 54: Essential Java classes mainly classes in the java.lang and java.io packages

Byte streams

• InputStream and OutputStream provide the API and partial implementation for input streams (streams that read 8-bit bytes) and output streams (streams that write 8-bit bytes).

• These streams are typically used to read and write binary data such as images and sounds.

• Two of the byte stream classes, ObjectInputStream and ObjectOutputStream, are used for object serialization

Page 55: Essential Java classes mainly classes in the java.lang and java.io packages

• As with Reader and Writer, subclasses of InputStream and OutputStream provide specialized I/O of two categories, : data sink streams (shaded), processing streams (unshaded)

Page 56: Essential Java classes mainly classes in the java.lang and java.io packages

• As with Reader and Writer, subclasses of InputStream and OutputStream provide specialized I/O of two categories, : data sink streams (shaded), processing streams (unshaded)

Page 57: Essential Java classes mainly classes in the java.lang and java.io packages

I/O super-classes• Reader and InputStream define similar APIs

but for different data types. For example, Reader contains these methods for reading characters and arrays of characters. – int read() – int read(char cbuf[]) – int read(char cbuf[], int offset, int length)

• InputStream defines the same methods but for reading bytes and arrays of bytes: – int read() – int read(byte cbuf[]) – int read(byte cbuf[], int offset, int length)

Page 58: Essential Java classes mainly classes in the java.lang and java.io packages

I/O super-classes• Writer and OutputStream are similarly parallel.

Writer defines these methods for writing characters and arrays of characters: – int write(int c) – int write(char cbuf[]) – int write(char cbuf[], int offset, int length)

• OutputStream defines the same methods for bytes: – int write(int c) – int write(byte cbuf[]) – int write(byte cbuf[], int offset, int length)

Page 59: Essential Java classes mainly classes in the java.lang and java.io packages

I/O streams

• All of the streams — readers, writers, input streams, and output streams — are automatically opened when created.

• Close a stream by calling its close method. A program should close a stream as soon as it is done with it, in order to free up system resources.

Page 60: Essential Java classes mainly classes in the java.lang and java.io packages

Using the streamsMemory CharArrayReader(Writer),

ByteArrayInput(Output)StreamStringReader(Writer), StringBufferInputStream

Pipe PipedReader(Writer), PipedInput(Output)Stream

File FileReader(Writer), FileInput(Output)Stream

Concatenate SequenceInputStream

Serialize ObjectInput(Output)Stream

Conversion DataInput(Output)Stream

Counting LineNumberReader(InputStream)

Lookahead PushbackReader(InputStream)

Printing PrintWriter(Stream)

Buffering BufferedReader(Writer), BufferedInput(Output)Stream

Filtering FilterReader(Writer), FilterInput(Output)Stream

Conversion byte vs. char

InputStreamReader, OutputStreamWriter

Page 61: Essential Java classes mainly classes in the java.lang and java.io packages

File stream• import java.io.*;

public class Copy { public static void main(String[] args) throws IOException { File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } }

• FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile);

Page 62: Essential Java classes mainly classes in the java.lang and java.io packages

Use pipe stream• FileReader words = new FileReader("words.txt");

Reader rhymingWords = reverse(sort(reverse(words)));

public static Reader reverse(Reader src) throws IOException {

BufferedReader in = new BufferedReader(src); PipedWriter pipeOut = new PipedWriter(); PipedReader pipeIn = new PipedReader(pipeOut); PrintWriter out = new PrintWriter(pipeOut); new ReverseThread(out, in).start(); return pipeIn; }

Page 63: Essential Java classes mainly classes in the java.lang and java.io packages

• public class ReverseThread extends Thread { private PrintWriter out; private BufferedReader in; public ReverseThread(PrintWriter out, BufferedReader

in) { this.out = out; this.in = in; } public void run() { if (out != null && in != null) { String input; while ((input = in.readLine()) != null) { out.println(reverseIt(input)); out.flush(); } out.close(); } } private String reverseIt(String source) { … } }

Page 64: Essential Java classes mainly classes in the java.lang and java.io packages

Wrap a stream

• BufferedReader in = new BufferedReader(source); ... PrintWriter out = new PrintWriter(pipeOut);

• The program reads from the BufferedReader, which in turn reads from source. The program does this so that it can use BufferedReader's convenient readLine method

• The PipedWriter is wrapped in a PrintWriter so that the program can use PrintWriter's convenient println method

Page 65: Essential Java classes mainly classes in the java.lang and java.io packages

Concatenate files• import java.io.*;

public class Concatenate { public static void main(String[] args) throws

IOException { ListOfFiles mylist = new ListOfFiles(args); SequenceInputStream s =

new SequenceInputStream(mylist); int c; while ((c = s.read()) != -1)

System.out.write(c); s.close();

} }

Page 66: Essential Java classes mainly classes in the java.lang and java.io packages

public class ListOfFiles implements Enumeration<FileInputStream> { private String[] listOfFiles; private int current = 0; public ListOfFiles(String[] listOfFiles) {

this.listOfFiles = listOfFiles; } public boolean hasMoreElements() {

if (current < listOfFiles.length) return true; else return false; } public FileInputStream nextElement() {

FileInputStream in = null; if (!hasMoreElements()) throw new Exception("No more

files."); else { String nextElement = listOfFiles[current];

current++; try { in = new FileInputStream(nextElement); } catch (FileNotFoundException e) {} }

return in; } }

Page 67: Essential Java classes mainly classes in the java.lang and java.io packages

Using filter streams

BufferedReader d = new BufferedReader(new

InputStreamReader(System.in)); String input; while ((input = d.readLine()) != null) {

... //do something interesting here }

Page 68: Essential Java classes mainly classes in the java.lang and java.io packages

Scanning • import java.io.*;

import java.util.*;

public class ScanFar { public static void main(String[] args) throws

IOException { Scanner s = new Scanner(new BufferedReader(

new FileReader("farrago.txt")));

while (s.hasNext()) { System.out.println(s.next());

} s.close();

} }

Page 69: Essential Java classes mainly classes in the java.lang and java.io packages

Formatting • public class Root {

public static void main(String[] args) { int i = 2; double r = Math.sqrt(i); System.out.format("The square root of %d is

%f.%n", i, r); }

}

Here is the output: The square root of 2 is 1.414214.

Page 70: Essential Java classes mainly classes in the java.lang and java.io packages

Formatting • %d formats an integer value as a decimal value; • %f formats a floating point value as a decimal value; • %n outputs a locale-specific line terminator. • %x formats an integer as a hexadecimal value; • %s formats any value as a string; • %tB formats an integer as a locale-specific month

name.

Page 71: Essential Java classes mainly classes in the java.lang and java.io packages

Object serialization

• Remote Method Invocation (RMI)--communication between objects via sockets

• Lightweight persistence--the archival of an object for use in a later invocation of the same program

Page 72: Essential Java classes mainly classes in the java.lang and java.io packages

Serializing objects

• FileOutputStream out = new FileOutputStream("theTime"); ObjectOutputStream s = new ObjectOutputStream(out); s.writeObject("Today"); s.writeObject(new Date()); s.flush();

• FileInputStream in = new FileInputStream("theTime"); ObjectInputStream s = new ObjectInputStream(in); String today = (String) s.readObject(); Date date = (Date) s.readObject();

Page 73: Essential Java classes mainly classes in the java.lang and java.io packages

Serializable objects

• public class MySerializableClass implements Serializable { ... }

• serialization of instances of this class are handled by the defaultWriteObject method of ObjectOutputStream – Class of the object – Class signature – Values of all non-transient and non-static members,

including members that refer to other objects • deserialize any instance of the class with the

defaultReadObject method in ObjectInputStream

Page 74: Essential Java classes mainly classes in the java.lang and java.io packages

New I/O package

• some programmers of high-performance applications will need the java.nio.* packages.

• These packages provide APIs for scalable I/O, fast buffered byte and character I/O, and character set conversion

• The New I/O APIs are designed for performance tuning — not day-to-day I/O programming

Page 75: Essential Java classes mainly classes in the java.lang and java.io packages

Contents

• Handling errors using exceptions

• Multi-threading

• I/O

• Setting program attributes

• Accessing system resources

Page 76: Essential Java classes mainly classes in the java.lang and java.io packages

Set program attributes• Java programs run within an environment that contains

system attributes: a host machine, a user, a current directory, and an operating system.

• A Java program also can set up its own configurable attributes, called program attributes.

• Program attributes allow the user to configure various startup options, preferred window size, and so on for the program.

• System attributes are maintained by the System class. Java programs can set their own set of program attributes through three mechanisms: – properties, – command-line arguments, and – applet parameters

Page 77: Essential Java classes mainly classes in the java.lang and java.io packages

Properties

• A property defines attributes on a persistent basis. • An attribute has two parts: a name and a value. For

example, “os.name” contains the name of the current operating system such as “Linux”

• The Properties class in the java.util package manages a set of key/value pairs. Each Properties key contains the name of a system attribute, and its corresponding Properties value is the current value of that attribute

• The System class uses a Properties object for managing system properties. Any Java program can use a Properties object to manage its program attributes

Page 78: Essential Java classes mainly classes in the java.lang and java.io packages

Life cycle of a program’s properties

Page 79: Essential Java classes mainly classes in the java.lang and java.io packages

Contents

• Handling errors using exceptions

• Multi-threading

• I/O

• Setting program attributes

• Accessing system resources

Page 80: Essential Java classes mainly classes in the java.lang and java.io packages

Access system resources

• The Java platform lets your program access system resources through a (relatively) system-independent API implemented by the System class and through a system-dependent API implemented by the Runtime class

Page 81: Essential Java classes mainly classes in the java.lang and java.io packages

Use the system class

• System.out • System.getProperty(argument); • class UserNameTest {

public static void main(String[] args) { String name; name =

System.getProperty("user.name"); System.out.println(name);

} }

Page 82: Essential Java classes mainly classes in the java.lang and java.io packages

The standard I/O streams

• Standard input--referenced by System.in– Used for program input, typically reads input

entered by the user.

• Standard output--referenced by System.out– Used for program output, typically displays

information to the user.

• Standard error--referenced by System.err– Used to display error messages to the user

Page 83: Essential Java classes mainly classes in the java.lang and java.io packages

System properties• file.separator File separator (for example, "/")• java.class.path Java class-path• java.class.version Java class version number• java.home Java installation directory• java.vendor Java vendor-specific string• java.vendor.url Java vendor URL• java.version Java version number• line.separator Line separator• os.arch Operating system architecture• os.name Operating system name• os.version Operating system version• path.separator Path separator (for example, ":")• user.dir User's current working directory• user.home User home directory• user.name User account name

Page 84: Essential Java classes mainly classes in the java.lang and java.io packages

Get / set system properties• System.getProperty("path.separator"); • import java.io.FileInputStream;

import java.util.Properties; public class PropertiesTest {

public static void main(String[] args) throws Exception {

// set up new properties object // from file "myProperties.txt" FileInputStream propFile =

new FileInputStream( "myProperties.txt");

Properties p = new Properties(System.getProperties()); p.load(propFile); // set the system properties System.setProperties(p); // display new properties System.getProperties().list(System.out); }

}

Page 85: Essential Java classes mainly classes in the java.lang and java.io packages

Forcing finalization and GC• Before an object is garbage collected, the Java

runtime system gives the object a chance to clean up after itself. This step is known as finalization and is achieved through a call to the object's finalize method. You can force object finalization to occur by calling System's runFinalization method.

• System.runFinalization(); This method calls the finalize methods on all objects that are waiting to be garbage collected.

• You can ask the garbage collector to run at any time by calling System's gc method: System.gc();

Page 86: Essential Java classes mainly classes in the java.lang and java.io packages

Provide own security manager

• The security manager is an application-wide object that determines whether potentially threatening operations should be allowed.

• The classes in the Java packages cooperate with the security manager by asking the application's security manager for permission to perform certain operations

Page 87: Essential Java classes mainly classes in the java.lang and java.io packages

Security manager

• SecurityManager appsm = System.getSecurityManager();

• SecurityManager security = System.getSecurityManager(); if (security != null) {

security.checkExit(status); } . . . // code continues here if checkedExit() returns

Page 88: Essential Java classes mainly classes in the java.lang and java.io packages

Write a security manager• class PasswordSecurityManager extends SecurityManager

{ . . . } • PasswordSecurityManager(String password) {

super(); this.password = password; } • private boolean accessOK() {

int c; DataInputStream dis = new

DataInputStream(System.in); String response; response = dis.readLine(); if (response.equals(password)) return true; else return

false; } • public void checkRead(String filename) {

if (!accessOK()) throw new SecurityException("No Way!"); }

• public void checkWrite(String filename) { if (!accessOK()) throw new SecurityException("Not

Even!"); }

Page 89: Essential Java classes mainly classes in the java.lang and java.io packages

Install a security manager

• try { System.setSecurityManager(

new PasswordSecurityManager(“some password")); } catch (SecurityException se) {

System.out.println("SecurityManager already set!"); }

Page 90: Essential Java classes mainly classes in the java.lang and java.io packages

Override methods of security manager• sockets checkAccept(String host, int port)

checkConnect(String host, int port) checkListen(int port)

threads checkAccess(Thread thread) class loader checkCreateClassLoader() file system checkDelete(String filename) checkLink(String library) checkRead(String filename) checkWrite(String filename) system commands checkExec(String command) interpreter checkExit(int status) package checkPackageAccess(String packageName) checkPackageDefinition(String packageName) properties checkPropertiesAccess() networking checkSetFactory() windows checkTopLevelWindow(Object window)

Page 91: Essential Java classes mainly classes in the java.lang and java.io packages

Other system methods

• System.exit(-1); • System.currentTimeMillis(); • System.arraycopy(

Object source, int srcIndex, Object dest, int destIndex, int length );

Page 92: Essential Java classes mainly classes in the java.lang and java.io packages

Runtime object

• Runtime objects provide two services. – First, they communicate with the components of the runtime

environment--getting information and invoking functions.

– Second, Runtime objects are also the interface to system-dependent capabilities