Title: Week 2
1Week 2
- Just Java by Linden chapters 4,5,13
- Java I/O and Client/Server
Some of the material on I/O and client/server is
from Bruce Eckels Thinking in Java
2Notes From Just Java
3Comments
// a single line comment / a multi-line
comment / / a javadoc
comment / javadoc MyDocumentedProgram.java
produces .html files
4Casts
// we can cast a float or double to an int with
truncation float f 3.142 int i (int) f //
we can cast an int to a short with
truncation short s (short) 123456
System.out.println(s)
C\McCarthy\www\JustJava\Examplesgtjava
TestCast -7616
5Char type
16-bit Unicode A single char constant looks like
A in single quotes. May be used as an unsigned
short char s (char) -1
int x s System.out.println(x)
C\McCarthy\www\JustJava\Examplesgtjava
TestUnsigned 65535
6String Class use .equals()
public class TestString public static void
main(String a) String x "A simple
string" String y "A simple" y
y " string" if(x y)
System.out.println("They are equal with ")
else if(x.equals(y))
System.out.println("They are equal with
.equals()") else
System.out.println("Not equal with or with
.equals()")
C\McCarthy\www\JustJava\Examplesgtjava
TestString They are equal with .equals()
7Notes From Just Java
Chapter 5
8Forward References
// works fine class Fruit void foo()
grams 22 int grams
9Arrays
Two steps int a a new
int10 Fruit b b new
Fruit345 // no Fruit objects yet
// dont
call b4.foo() See book for
initialization syntax.
10Arrays can be cloned
public class TestSheep public static void
main(String a) int sheep new
int10 sheep4 99 int
baaa (int) sheep.clone()
System.out.println(baaa4)
C\McCarthy\www\JustJava\Examplesgtjava
TestSheep 99
11Most operators are the same as c
Order of operations is clearly defined in
Java. Precedence says which operators bind
first. Associativity is the tie breaker when
operators are of equal precedence. Order of
operations is strictly left to right in Java.
12Example
public class TestSheep public static void
main(String a) int i 8
int m new int10 mi (i 2)
i System.out.println("m8 "
m8 " and i " i)
C\McCarthy\www\JustJava\Examplesgtjava
TestSheep m8 4 and i 3
13What Happens on Overflow?
When an integer valued expression is too big for
its type the lowend bytes are stored and we have
no report of overflow. byte b (int)
10000 An exception is thrown for division by 0.
14Example
public class TestOverflow public static
void main(String a) byte i 8
byte m 0 i (byte) (i m)
C\McCarthy\www\JustJava\Examplesgtjava
TestOverflow Exception in thread "main"
java.lang.ArithmeticException / by zero
at TestOverflow.main(TestOverflow.java7)
15Adding a try/catch block
public class TestOverflow public static
void main(String a) try
byte i 8 byte m 0
i (byte) (i m)
catch(ArithmeticException e)
System.out.println("That did not go well")
System.out.println("Terminating")
C\McCarthy\www\JustJava\Examplesgtjava
TestOverflow That did not go well Terminating
16Notes From Bruce Eckels Thinking in Java
Just Java Chapter 13
Simple I/O
17JAVA I/O and Client/Server
18The Java IO System
Different kinds of IO Files, the console,
blocks of memory, network connections
Different kinds of operations Sequential,
random- access, binary, character, by lines,
by words, etc.
Source Eckel
19The Java IO Library Design
Seems like a lot of classes Also seems at
first like an odd design Not typically how you
think of using classes Can require a lot of
typing There is a plan A learning experience
in class design The Decorator Design Pattern
Source Eckel
20InputStream and OutputStream
InputStream (Abstract class) This abstract
class is the superclass of all classes
representing an input stream of bytes.
OutputStream (Abstract class) This abstract
class is the superclass of all classes
representing an output stream of bytes.
Source Eckel
21Types of InputStream
ByteArrayInputStream read memory
block StringBufferInputStream read from String
(not buffer) FileInputStream
read from file PipedInputStream
read from another thread SequenceInputStream
reads from several streams FilterInputStream
Decorators subclass this class.
A FilterInputStream
contains some other input stream, which it uses
as its basic source of data, possibly
transforming the data along the way or providing
additional functionality.
22Two important FilterInputStream classes --
Decorators
- DataInputStream (binary data)
- Full interface for reading primitive and
built- in types - Construct with an InputStream
- When reading a float, four bytes are read
- BufferedInputStream
- Adds buffering to the stream (usually do this)
- Construct with an InputStream
23FileInputStream - Reading Data From a
File BufferedInputStream Buffers
input DataInputStream Reading binary data
readLine() -- deprecated
DataInputStream
BufferedInputStream
Decorators
FileInputStream
Source of data
File Name
String
24// copy a binary or text file import
java.io. public class CopyBytes public static
void main( String args) throws IOException
DataInputStream in
new DataInputStream( new
BufferedInputStream(
new FileInputStream(args0)))
DataOutputStream out new
DataOutputStream( new
BufferedOutputStream(
new FileOutputStream(args1)))
25byte byteIn try
while(true) byteIn
in.readByte()
out.writeByte(byteIn)
catch(EOFException e)
in.close()
out.close()
26Types of OutputStream Writes to
ByteArrayOutputStream Block of
memory FileOutputStream
File PipedOutputStream
Pipe (to another thread) FilterOutputStream
Decorators subclass
this
class
27Three important FilterOutputStream classes --
Decorators
DataOutputStream Full interface for
writing primitive and built-in types complements
DataInputStream for portable reading
writing of data DataOutputStream is
normally for storage. PrintStream Allows
primitive formatting for data display. Not as
nice a cs printf(). Converts arguments to
ASCII or EBCDIC. Use PrintWriter when
writing Unicode characters rather than bytes.
BufferedOutputStream Adds a buffer (usually
do this).
28Writing ASCII Data To A File PrintStream writes
in the platforms default encoding.
PrintStream
BufferedOutputStream
Decorators
FileOutputStream
File Name
Sink
String
29// Writing ASCII data to a file import
java.io. public class OutPutDemo public
static void main(String args) throws
FileNotFoundException PrintStream out
new PrintStream(
new BufferedOutputStream(
new FileOutputStream("I
ODemo.out"))) out.println("Hello
world...on a file") out.close()
30DataOutPutStream is for binary output. DataInputSt
ream is for reading binary.
DataOutputStream
BufferedOutputStream
Decorators
FileOutputStream
Sink
String
31// Writing data to a file In Binary not ASCII
import java.io. public class OutPutDemo
public static void main(String args) throws
FileNotFoundException, IOException
DataOutputStream out new DataOutputStream (
new
BufferedOutputStream(
new FileOutputStream("Binary.out"))
) out.writeDouble(3.34) // cant view
this!! out.writeDouble(2.33)
out.close()
32Readers and Writers
- New in Java 1.1
- Provide Unicode-compliant, character-based I/O
- Similar in structure to the InputStream and
OutputStream - byte hierarchy
33PrintWriter has replaced PrintStream for text
output.
PrintWriter
BufferedWriter
Decorators
FileWriter
String
Sink
34// Writing data to a file -- improves on the old
PrintStream import java.io. public class
OutPutDemo public static void main(String
args) throws FileNotFoundException,
IOException PrintWriter out new
PrintWriter(
new BufferedWriter(
new FileWriter("IODemo.out"))
) out.println("Hello world...on a
file") out.close()
35Converting from an 8-bit InputStream to 16-bit
Unicode
BufferedReader
Converts from an InputStream to a Reader
InputStreamReader
Inputstream
A System.in object is of type InputStream
36import java.io. public class InputDemo public
static void main(String args) throws
IOException BufferedReader in
new BufferedReader(
new InputStreamReader(System.in))
System.out.println("What is your
name?") String name in.readLine()
System.out.println("Hello " name)
37BufferedReader
InputStreamReader
Reader
FileInputStream
InputStream
String
38import java.io. // Read
and write an ASCII file public class InputDemo
public static void main(String args) throws
IOException BufferedReader in
new BufferedReader(
new InputStreamReader(
new FileInputStream("IODemo.in
"))) String
line while((line in.readLine()) !
null)
System.out.println(line)
39Some Examples
// Demonstrate character I/O in Java // Count the
number of a's and b's import java.io. public
class CharIO public static void main(String
arg) throws IOException
InputStreamReader is new InputStreamReader(Syste
m.in) System.out.println("Enter a line of
text and I'll count the a's and b's")
40 int aCount 0 int bCount 0 int
i // i should be an int so that we can detect
a -1 from
// the read method. -1 is returned when read()
sees // ltctrlgtltzgt in
DOS i is.read()
while(i ! '\n') char c
(char) i if(c 'a') aCount if(c 'b')
bCount i
is.read() System.out.println("a total "
aCount " b total " bCount)
41Some Examples Count
lines
// Demonstrate character I/O in Java // Echo the
input and count lines import java.io. public
class CharIO2 public static void main(String
arg) throws IOException
InputStreamReader is new InputStreamReader(Syste
m.in)
42 System.out.println("I'll echo and count
lines") int lineCount 0 int i i
is.read() // -1 EOF ltctrlgtltzgt in
DOS while(i ! -1) char c (char) i if(c
'\n') lineCount System.out.print(c)
i is.read() System
.out.println("--------------------------") Syste
m.out.println("Line count " lineCount)
43Some Examples Using StringTokenizer
// Read a line of integers // and display their
sum import java.io. import java.util. //
for StringTokenizer public class LineOfInts
public static void main(String arg) throws
IOException
44 InputStreamReader is new InputStreamReader(S
ystem.in) BufferedReader br new
BufferedReader(is) StringTokenizer st
System.out.println("Enter a line of integers")
String s br.readLine() // use comma,
space, and tab for delimeters t new
StringTokenizer(s, ", \t")
45 int sum 0 while(st.hasMoreElements(
)) int val Integer.parseInt(st.nextToken())
sum val System.out.println("The sum
is " sum)
46Some Examples Formatting a double
// display a number rounded to two decimal
places // at least one digit to the left of the
decimal point // means a digit, 0 shows as
absent import java.io. import java.text.
public class FormattedOutput static final
double myDouble 456.346 public static void
main(String arg) throws IOException
DecimalFormat df new DecimalFormat("0.00")
System.out.println(df.format(myDouble)) //
displays 456.35
47Some Examples
// Java I/O // Read a double and display its
square root import java.io. public class
DoubleIO public static void main(String
arg) throws IOException
InputStreamReader is new InputStreamReader(Syste
m.in) BufferedReader br new
BufferedReader(is)
48 double x System.out.println("Enter a
double and I'll compute the square root")
String inputString br.readLine() x
Double.parseDouble(inputString) //
displays NAN if x lt 0 System.out.println("The
square root of "x" is " Math.sqrt(x))
49Object Serialization I/O
- Save or restore an object
- Works across networks (RMI arguments and return
values) - Compensates for differences in operating systems
- All relevant parts of an Object magically
- stored and retrieved even web of objects
50Object serialization
Class must implement Serializable Wrap a
stream in a ObjectOutputStream (for
writing) or ObjectInputStream
(for reading) Use writeObject(Â ) and
readObject(Â )
51An Example Writing BigIntegers
Use OutputStream NOT Writer
import java.math. import java.io. public
class TestBigInts // Streams work with
binary bytes public static void main(String
args) throws IOException
BigInteger x new BigInteger("1234567891011121314
") BigInteger y new
BigInteger("1234567890000000000")
ObjectOutputStream out new ObjectOutputStream(
new
FileOutputStream("bigints.dat"))
out.writeObject("Big Integer Storage")
out.writeObject(x) out.writeObject(y)
52Another Example Reading BigIntegers
import java.math. import java.io. public
class TestBigInts public static void
main(String args) throws IOException,
ClassNotFoundException BigInteger x,
y ObjectInputStream in new
ObjectInputStream(
new FileInputStream("bigints.dat"))
String s (String)in.readObject()
x (BigInteger)in.readObject() y
(BigInteger)in.readObject()
System.out.println(s " " x " " y)
53Some Examples List serialization
import java.util. import java.io. public
class SaveAList implements Serializable
public static void main(String args)throws
IOException, ClassNotFoundException
LinkedList stack new LinkedList()
stack.addFirst("Little Cat A")
stack.addFirst("Little Cat B")
stack.addFirst("Little Cat C")
54 ObjectOutputStream out new
ObjectOutputStream( new
FileOutputStream("CatStack.out"))
out.writeObject("The cat and the hat's hat
cats") out.writeObject(stack)
out.close() ObjectInputStream in new
ObjectInputStream( new
FileInputStream("CatStack.out"))
String s (String) in.readObject()
LinkedList anotherStack (LinkedList)
in.readObject() System.out.println(s
anotherStack)
55Output
C\McCarthy\46935\io\Serializationgtjava
SaveAList The cat and the hat's hat catsLittle
Cat C, Little Cat B, Little Cat A
56I/O on the Net
Historically error- prone, difficult, complex
Threading is very useful and relatively easy
here Excellent reference Java Network
Programming by Elliotte Rusty Harold, OReilly
Books, 1997.
Source Eckel
57Identifying a Machine
Uniquely identify a machine from all the others
in the world IP (Internet Protocol) address
that can exist in two forms 1) DNS
(Domain Name Service) form
hempel.heinz.cmu.edu 2) Dotted quad
form 128.2.240.92 Represented internally by
32 bit number (4.3 billion possibilities.
Oops!) (going to 128) static InetAddress.getByNa
me( ) produces a Java object containing address
Source Eckel
58Servers Clients
Two machines must connect Server waits
around for connection Client initiates
connection Once the connection is made, server
client look identical Both ends are
turned into InputStream and OutputStream
objects, which can then be converted to Reader
and Writer objects
Source Eckel
59Testing w/ o a Network
- You might not trust your code
- localhost the local loopback IP address
- for testing without a network InetAddress addr
- InetAddress.getByName(null)
- Equivalently InetAddress.getByName("localhost")
- Or using the reserved IP number for the
- loopbackInetAddress.getByName("127.0.0.1")
- open two windows and talk
60Port Unique Place in a Machine
- IP address isnt enough to identify a unique
- server
- Many servers can exist on one machine
- Protocol Port
- http server 80
- ftp server 21
- telnet 23
- finger 79
- A server is a program watching a port.
61Ports
When you set up client and server, you must
specify IP address and port, so they can
find each other Not a physical location,
but a software abstraction to represent a
service 1- 1024 are reserved (on Unix, root may
access these ports), higher numbered ports
are available
62Sockets
Software abstraction used to represent the
terminals of a connection between two
machines Socket is the actual 2- way
connector. Can initiate a connection with a
server ServerSocket isnt really a socket but
more of a ServerConnector that produces a
Socket as the return value of accept(Â ) ,
which waits (blocks) for a connection. In the
end, you get a Socket on each machine
63Just Like Files... Once you have a Socket ,
you call getInputStream( ) and getOutputStream(
) to produce the corresponding InputStream
and OutputStream objects You convert these to
readers and writers, wrap them in a
BufferedReader or BufferedWriter and
PrintWriter From then on, its like reading
and writing any other IO stream!
64Some Examples Client/Server
// JabberServer. Java From Bruce Eckels text //
Very simple server that just // echoes whatever
the client sends. // One client at a time. No
threads yet! import java. io. import java.
net. public class JabberServer // Choose a
port outside of the range 1- 1024 static final
int port 8080 public static void main(
String args )
65try boolean flush true
ServerSocket s new ServerSocket(port)
System. out. println(" Server Started " s)
// Blocks until a connection occurs
Socket socket s.accept() System. out.
println( "Connection accepted, socket "
socket) BufferedReader in new
BufferedReader(
new InputStreamReader(
socket.getInputStream())) PrintWriter
out new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())), flush)
66 while (true) // till client says END
String str in.readLine() if
(str.equals("END")) break
System.out.println(" Echoing " str)
out.println(str) System.out.println("
closing...") socket.close() catch(
Exception e) e.printStackTrace()
67// JabberClient. Java from Bruce Eckels text //
Very simple client that just sends // lines to
the server and reads lines that the server
sends. import java. net. import java.
io. public class JabberClient // Choose a
port outside of the range 1- 1024 static final
int port 8080 public static void main( String
args) try // Produce "Local
Loopback" IP address InetAddress addr
InetAddress.getByName(null) System.out.
println(" addr " addr) Socket socket
new Socket(addr, port) // remote server
System.out.println(" socket " socket)
68BufferedReader in new BufferedReader(
new InputStreamReader(
socket.getInputStream())) // Enable PrintWriter
autoflush PrintWriter out new PrintWriter(
new
BufferedWriter(
new OutputStreamWriter(
socket.
getOutputStream())), flush)
69 for( int i 0 i lt 10 i )
out. println(" howdy " i) String
str in. readLine() System. out.
println( str) out. println(" END")
catch( Exception e) e.
printStackTrace()
70Lab Problem Discussion
From Just Java page 378 Modify the program
below (Dump.java) so that it also outputs any
printable bytes in a set of columns to the right
of the hex dump on each line. Print the
character if it has a printable form, and print a
. if it does not. This ensures that lines
are the same length and columns line up. The
program Dump.java is also found on page 371 of
Just Java.
71// This program hex dumps the contents of the
file // whose name is given as a commandline
argument. import java.io. public class Dump
static FileInputStream myFIS null
static FileOutputStream myFOS null static
BufferedInputStream myBIS null static
PrintStream myPOS null static public void
main(String arg) if (arg.length0)
System.out.println("usage java Dump
somefile") System.exit(0)
72PrintStream e System.err try
myFIS new FileInputStream( arg0 )
myFOS new FileOutputStream( arg0
".hex" ) myBIS new
BufferedInputStream(myFIS) // the
"true" says we want writes flushed to disk with
// each newline myPOS new
PrintStream ( new
BufferedOutputStream(myFOS), true)
myPOS.print("Hex dump of file " arg0)
int i while ( (imyBIS.read())
! -1 ) dump( (byte) i )
73 catch(IOException x)
e.println("Exception " x.getMessage() )
static private long byteCount 0
static private void dump(byte b)
if (byteCount 16 0) // output
newline and the address every 16 bytes
myPOS.println() // pad leading
zeros in address. String addr
Long.toHexString(byteCount) while
(addr.length() lt 8) addr "0" addr
myPOS.print( addr "" )
74// output a space every 4 bytes if
(byteCount 4 0)
myPOS.print(" ") // dump the
byte as 2 hex chars String s
Integer.toHexString( b 0xFF ) if
(s.length()1) s "0" s myPOS.print(
s.charAt(0) ) myPOS.print( s.charAt(1)
" " )