Java API Essentials

Web Languages Course 2009 University of Trento

Lab Objective 

Refresh basic Java concepts on

• I/O Streams; • Object Serialization; • Simple Client-Server applications through Sockets

2

I/O Streams in Java

Task objectives:  Refresh the principles of I/O usage in Java;  Understand the difference between Streams and Reader/Writer objects;

Introduction  

  

A stream is a sequence of data An I/O Stream represents an input source or an output destination. A program uses an input stream to read data from a source, one item at a time A program uses an output stream to write data to a destination, one item at time Three streams are created for us automatically:

• System.in -> standard input stream • System.out -> standard output stream • System.err -> standard error

4

Basic input and output classes  

The java.io package has a large number of classes Most of the classes consist of:

• •







Byte streams  subclasses of InputStream or OutputStream Character streams  subclasses of Reader and Writer

InputStream and OutputStream classes read and write 8-bit bytes Reader and Writer classes read and write 16-bit Unicode characters ObjectInputStream and ObjectOutputStream classes read and write entire objects 5

What to use? 

Depends…



Use InputStream and OutputStream classes if you use binary data (e.g., integers, doubles)



Use Reader and Writer classes if you use text data



Use ObjectInputStream and ObjectOutputStream classes if your data is an object 6

Sources and sinks for data 

What is the source of your data?



What will be consuming your output data?



Many ways to input or output your data: files, strings, arrays of characters, sockets.



Any of these can be a source for an InputStream or Reader or a sink for an OutputStream or Writer

7

Input stream classes

8

Output stream classes

9

I/O from the Command Line

1



the standard input stream System.in read bytes from the console, while the standard ouput stream System.out can print number and strings



Since data from keyboard are composed of characters, the byte-to-character "bridge" streams InputStreamReader is used to convert bytes in characters: InputStreamReader reader = new InputStreamReader(System.in); 10

I/O from the Command Line

2



InputStreamReader reads one character at time



What if I want to read a whole string?



The class BufferedReader is used BufferedReader console = new BufferedReader (new InputStreamReader(System.in));



The method readLine()is used to read the string String input = console.readLine(); 11

Exercise 1: ConsoleInputTest.java 



Write a simple program that reads a string of characters from the console and print them into the std output (System.out) The program ends when “BYE” is digited

12

HINTs

Exercise 1: ConsoleInputTest.java

import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); … String input = console.readLine(); … System.out.println(input);

13

import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException;

Exercise 1: ConsoleInputTest.java

public class ConsoleInputTest { public ConsoleInputTest() { } /** @param args the command line arguments */ public static void main(String[] args) throws IOException { BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); System.out.println("This is a simple example on how to read data from the console"); System.out.println("Please, enter characters"); while(true) { String input = console.readLine(); if (input.trim().equals("BYE")) System.exit(0); System.out.println(input); } } } 14

File I/O byte streams 





1

Class FileInputStream: obtains input bytes from a file in a file system Constructors: FileInputStream(String filename), FileInputStream(File file) Methods:

• int

• int

read(): reads a byte of data from this input stream.

read(byte[] b): reads up to b.length bytes of data from this input stream into an array of bytes. • void close(): closes this file input stream and releases any system resources associated with it.

15

File I/O byte streams 





2

Class FileOutputStream: output stream for writing data to a File Constructors: FileOutputStream(String filename), FileOutputStream(File file) Methods:

• int

write(int b): write the specified byte to this output stream.

• int

write(byte[] b): writes b.length bytes from the specified byte array to this file output stream. • void close(): closes this file output stream and releases any system resources associated with it. 16

Exercise 2: Copy bytes from file1 to file2 

Hints

• •

Create a text file (e.g., input.txt) from where to read data Write a Java program that uses FileInputStream and FileOutputStream classes and their methods

import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; ... try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; ... } catch (IOException e) { System.out.println(e.getMessage()); } …. 17

Exercise 2: Copy bytes from file1 to file2 

Solution

package it.unitn.web.streams;

while ((c = in.read()) != -1) { out.write(c); }

import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException;

in.close(); out.close();

public class CopyBytes {

System.out.println(“done!");

public static void main(String[] args) {

} catch (IOException e) { System.out.println(e.getMessage()); } }

FileInputStream in = null; FileOutputStream out = null; try {

}

in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; 18

Exercise 3: Copy characters from file1 to file2 

Hints

• Use the same text file (e.g., input.txt) as before

• Write a Java program that uses FileReader and FileWriter classes and their methods

• http://java.sun.com/j2se/1.5.0/docs/api/index.html

19

Exercise 3: Copy characters from file1 to file2 

Solution

package it.unitn.web.streams;

while ((c = in.read()) != -1) { out.write(c); }

import java.io.FileReader; import java.io.FileWriter; import java.io.IOException;

in.close(); out.close();

public class CopyBytes {

System.out.println(“done!");

public static void main(String[] args) {

} catch (IOException e) { System.out.println(e.getMessage()); } }

FileReader in = null; FileWriter out = null; try {

}

in = new FileReader("input.txt"); out = new FileWriter("output.txt"); int c; 20

Exercise 4: Copy lines from file1 to file2 

Hints

• •

Create a text file (e.g., input.txt) from where to read data Write a Java program that uses BufferedReader and PrintWriter classes and their methods

… import java.io.BufferedReader; ... try { in = new BufferedReader( new FileReader("input.txt")); out = new PrintWriter( new FileWriter("output.txt")); String line; ... } catch (IOException e) { System.out.println(e.getMessage()); } ….

21

Exercise 4: Copy lines from file1 to file2 

Solution

package it.unitn.web.streams; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.BufferedReader; import java.io.PrintWriter; public class CopyLines {

out = new PrintWriter( new FileWriter("output.txt")); String line; while ( (line = in.readLine()) != null) { out.println(); } in.close(); out.close();

public static void main(String[] args) {

System.out.println(“done!");

BufferedReader in = null; PrintWriter out = null; try { in = new BufferedReader( new FileReader("input.txt"));

} catch (IOException e) { System.out.println(e.getMessage()); } } }

22

Buffered Streams 

CopyBytes.java and CopyCharacters.java used unbuffered I/O. This means each read or write request is handled directly by the underlying OS.



ConsoleInputTest.java and CopyLines.java used buffered I/O streams.



Buffered input/output streams read/write data from/to a memory area known as a buffer; the native input API is called only when the buffer is empty/full 23

Exercise 2: GZIP compression    

Create a text file Compress the file by using the GZIP format; Decompress the GZIP file and put it into another file Check if the two files are the same

Hint: Use GZIPOutputStream and GZIPInputStream

24

Object Serialization

Example of writing on file

The serialization process 



1

The ability for an object to exist beyond the execution of the program which has created it, is called persistence The Java Serialization API provides a standard mechanism for developers to implement object persistence.

• •

Object serialization is the process of saving an object's state to a sequence of bytes, as well as the process of rebuilding those bytes into a live object at some future time. Such mechanism allows, for example, to save the object’s state in a file, move it through the network and use it in distributed applications.

26

The serialization process

2



An object’s state is composed by its class, its primitive fields and its referenced objects



Serializing an object means to transfer the entire web of object references into a stream



In Java few lines of code allow to save/restore the state of an object into/from a stream



Classes ObjectOutputStream and ObjectInputStream are used for serialization and deserialization

27

The serialization process

3

Rule #1: The object to be persisted must implement the Serializable interface or inherit that implementation from its object hierarchy. 

Not all the classes implement the interface Serializable (e.g, Object, Thread, Sockets)

• 

Try the command “serialver –show” to check if a class is serializable

What if we have a class that contains an instance of Thread?

Rule #2: The object to be persisted must mark all nonserializable fields transient 28

Example: Serialization on file 

Steps:

1. Create a persistent object (e.g., current time and date) 2. Save object into a file 3. Restore this info from the file, print it on the screen together with time and date occurring at the time of printing 

Expected output (after step 3) : Flattened time: Thu Sep 15 14:21:09 CEST 2005 Current time: Thu Sep 15 14:22:11 CEST 2005 29

Step 1: Create a persistent object package flatten; import java.io.Serializable; import java.util.Date; import java.util.Calendar; public class PersistentTime implements Serializable { private Date time; PersistentTime() { time = Calendar.getInstance().getTime(); } //Return the date public Date getTime() { return time; } } 30

Step 2: Save object into a file import java.io.ObjectOutputStream; import java.io.FileOutputStream; ... public class FlattenTime { public static void main(String [] args) { ... PersistentTime time = new PersistentTime(); ... fos = new FileOutputStream(filename); out = new ObjectOutputStream(fos); out.writeObject(time); out.close(); ... } } 31

import java.io.ObjectOutputStream; import java.io.FileOutputStream; Import java.io.IOExcception

public class FlattenTime { public static void main(String [] args) { String filename = "time.ser"; if(args.length > 0) filename = args[0]; PersistentTime time = new PersistentTime(); FileOutputStream fos = null; ObjectOutputStream out = null;

try { fos = new FileOutputStream(filename); out = new ObjectOutputStream(fos); out.writeObject(time); out.close(); } catch(IOException ex) { ex.printStackTrace(); } } } 32

Exercise (30 min.)  

Execute serialization on file (step1, step2) Implement step3: write a Java program that, given a serialized file   

 

Restore its content (e.g., time and date) Print it on the screen For checking, display also time and date occurring at the time of printing

Hints: Use classes, FileInputStream, ObjectInputStream and method readObject Expected output: Flattened time: Thu Sep 15 14:21:09 CEST 2005 Current time: Thu Sep 15 14:22:11 CEST 2005 33

public class InflateTime { public static void main(String [] args) { String filename = "time.ser"; if(args.length > 0) filename = args[0];

Solution

PersistentTime time = null; FileInputStream fis = null; Explicit Cast ObjectInputStream in = null; try { fis = new FileInputStream(filename); in = new ObjectInputStream(fis); time = (PersistentTime)in.readObject(); in.close(); } catch(IOException ex) { ex.printStackTrace(); } catch(ClassNotFoundException ex) { ex.printStackTrace(); } System.out.println("Flattened time: " + time.getTime()); System.out.println(); System.out.println("Current time: " + Calendar.getInstance().getTime()); } } 34

Exercise: object serialization (20 min.) 

 



Create an ArrayList object and fill it with 3-5 String object; Save the ArrayList object on disk Restore the object from disk and copy it in another ArrayList object Check if the two objects are the same

35

Client-Server Applications through Sockets

The package java.net.*

Outline 

 



Client Server Architecture Simple Client Server Application The java.net package Example Using Object Serialization

37

Client Server Architecture 

The commonly used model for Distributed Applications



The client is a process accessing the remote resource and the server provides the access to the resource 38

A simple client server application 

Client  Connects to a server  Sends a message to the server  Waits for response  Prints the response to the standard output



Server  Waits for a client to connect  Receives a message from the client  Send the message back to the client 39

The java.net package 

The package java.net provides support for sockets programming



The package java.net contains: Socket, URL, InetAddress, ServerSocket, etc.



Sockets + Object Serialization: combine java.net and java.io.Serializable to transport Java objects through the network

40

The class InetAddress

1



The java.net.InetAddress class represents Internet Protocol (IP) address



It converts numeric addresses to host names and host names to numeric addresses.



It is used by other network classes like Socket and ServerSocket to identify hosts



There are no public InetAddress() constructors. Arbitrary addresses may not be created. 41

The class InetAddress

2



Host name-to-IP address resolution is accomplished through the use of a combination of local machine configuration information and network naming services such as the Domain Name System (DNS) and Network Information Service(NIS)



The particular naming services(s) being used is by default the local machine configured one. For any host name, its corresponding IP address is returned.

42

The class InetAddress

3

Static methods: 

getLocalHost()  Returns the local host.



getByName(String host)  Returns the IP address of a host, given the host's name



getAllByName(String host)  Returns an array of its IP addresses, based on the configured name service on the system.

43

Exercise: InetAddressTest.java import java.net.*; /** * Testing class InetAddress: */ class InetAddressTest { /** Creates a new instance of InetAddressTest */ public InetAddressTest() { }

/** @param args the command line arguments */ public static void main(String[] args) throws UnknownHostException { InetAddress address = InetAddress.getLocalHost(); System.out.println(address); System.out.println(address.getHostName()); } } 44

Example: NSLookupApp.java … try { if(args.length!=1){ System.out.println("Usage: java NSLookupApp hostName"); return; }

InetAddress host = InetAddress.getByName(args[0]); String hostName = host.getHostName(); System.out.println("Host name: "+hostName); System.out.println("IP address: "+host.getHostAddress()); }catch(UnknownHostException ex) { System.out.println("Unknown host"); return; 45

Sockets 

Endpoint of a two-way communication link between two programs running on the network.



An endpoint is a combination of an IP address and a port number.



Every TCP connection can be uniquely identified by its two endpoints.

46

TCP Sockets



Connection-oriented sockets, almost always based on TCP java.net.ServerSocket



java.net.Socket



• Implements the server side of the connection • Used to listen for connection requests from clients; • Should be bound to a known port to listen on, • Its accept method blocks until a client requests a connection • Implements the client side of the connection • Used to connect to a specific port in a server machine 47

Socket TCP Constructor

Create

Socket(String host, int port)

a stream socket and connects it to the specified port number on the named host.

Socket(InetAddress address, int port)

a stream socket and connects it to the specified port number at the specified IP address

ServerSocket(int port)

a server socket, bound to the specified port .

ServerSocket(int port, int backlog )

a server socket and binds it to the specified local port number, with the specified backlog (maximum queue length for incoming connection) 48

Example: “ the echo application” 



EchoClient .java

• • • •

Creates a socket thereby getting a connection to the Echo server. Reads input from the user on the standard input stream Forwards that text to the Echo server by writing it to the socket Reads and displays the data passed back to it from the server

EchoServer.java

• • • •

Creates a server socket to accept connections from clients. Establishes connection to the client Reads from the socket (receives data from the client) Writes to the socket (sends data to the client)

49



EchoClient try { //Create connection to the server "localhost" on port 8189 s = new Socket("localhost",8189); //Set streams to read from and write to a socket s_in = new BufferedReader(new InputStreamReader(s.getInputStream())); s_out = new PrintWriter(s.getOutputStream(),true); System.out.println(s_in.readLine()); //Set input stream for reading from console console = new BufferedReader(new InputStreamReader(System.in)); String user_input; String received; while(true){ user_input = console.readLine(); s_out.println(user_input); received = s_in.readLine(); System.out.println(received); } … 50

EchoServer try { ServerSocket s = new ServerSocket (8189); //Wait for the client Socket incoming = s.accept (); System.out.println(“Connection requested from host: " + incoming.getInetAddress().getHostName() + "\nto port: " + incoming.getLocalPort() + "\nfrom port: " + incoming.getPort() + "\nwith IP: " + incoming.getInetAddress().getHostAddress()); BufferedReader in = new BufferedReader (new InputStreamReader (incoming.getInputStream ())); PrintWriter out = new PrintWriter (incoming.getOutputStream (), true); out.println ("Hello! Enter BYE to exit."); 51

EchoServer boolean go = true; String line; while (go){ line = in.readLine (); out.println ("Echo: " + line); if (line.trim().equals("BYE")){ go = false; } } incoming.close () } catch (IOException e) { System.out.println ("Error. " + e); }

52

Socket Timeout 

If data are not available (e.g., the host is not reachable), the reading methods remain blocked



To solve the problem: use the setSoTimeout() method Socket s = new Socket(…); s.setSoTimeout(1000); //time out in millisecond



When a timeout is set, all the following operations throw the exception InterruptedIOException 53

References 

Bruce Eckel, Thinking in Java, 3rd Edition



IBM developerWorks: New to Java technology



http://java.sun.com/developer/technicalArticles/Progr amming/serialization/



http://java.sun.com/developer/technicalArticles/ALT/s ockets/ 54