View
222
Download
0
Embed Size (px)
Citation preview
1
Week 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 BruceEckel’s “Thinking in Java”
2
Notes From “Just Java”
Chapter 4
3
Comments
// a single line comment
/* a multi-line comment*/
/** a javadoc comment*/
javadoc MyDocumentedProgram.java produces .html files
4
Casts// we can cast a float or double to an int with truncationfloat f = 3.142;int i = (int) f;
// we can cast an int to a short with truncationshort s = (short) 123456; System.out.println(s);
C:\McCarthy\www\JustJava\Examples>java TestCast-7616
5
Char 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\Examples>java TestUnsigned 65535
6
String 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\Examples>java TestString
They are equal with .equals()
7
Notes From “Just Java”
Chapter 5
8
Forward References
// works fine
class Fruit {
void foo() { grams = 22; } int grams;}
9
Arrays
Two steps:
int a[]; a = new int[10];
Fruit b[]; b = new Fruit[345]; // no Fruit objects yet // don’t call b[4].foo()
See book for initialization syntax.
10
Arrays can be cloned
public class TestSheep {
public static void main(String a[]) {
int sheep[] = new int[10]; sheep[4] = 99; int baaa[] = (int[]) sheep.clone(); System.out.println(baaa[4]); }}
C:\McCarthy\www\JustJava\Examples>java TestSheep99
11
Most 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 equalprecedence.
Order of operations is strictly left to right in Java.
12
Examplepublic class TestSheep {
public static void main(String a[]) {
int i = 8; int m[] = new int[10];
m[i] = (i = 2) * i++; System.out.println("m[8] == " + m[8] + " and i == " + i);
}} C:\McCarthy\www\JustJava\Examples>java TestSheep
m[8] == 4 and i == 3
13
What Happens on Overflow?
When an integer valued expression is too big for itstype the lowend bytes are stored and we have no report of overflow.
byte b = (int) 10000;
An exception is thrown for division by 0.
14
Examplepublic class TestOverflow {
public static void main(String a[]) {
byte i = 8; byte m = 0; i = (byte) (i % m);
}}
C:\McCarthy\www\JustJava\Examples>java TestOverflowException in thread "main" java.lang.ArithmeticException: / by zero at TestOverflow.main(TestOverflow.java:7)
15
Adding a try/catch blockpublic 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\Examples>java TestOverflowThat did not go wellTerminating
16
Notes From Bruce Eckel’s Thinking in Java
“Just Java” Chapter 13
Simple I/O
17
JAVA I/O and Client/Server
18
The 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
19
• 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
The Java IO Library Design
Source: Eckel
20
• 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.
InputStream and OutputStream
Source: Eckel
21
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.
Types of InputStream
22
• 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
Two important FilterInputStream classes -- Decorators
23
FileInputStream - Reading Data From a FileBufferedInputStream – Buffers inputDataInputStream – Reading binary data readLine() -- deprecated
File Name
File Name
DataInputStream
BufferedInputStream
FileInputStream
String Source of data
Decorators
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(args[0])));
DataOutputStream out =
new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(args[1])));
25
byte byteIn;
try {
while(true) {
byteIn = in.readByte();
out.writeByte(byteIn);
}
}
catch(EOFException e) {
in.close();
out.close();
}
}
}
26
ByteArrayOutputStream Block of memory
FileOutputStream File
PipedOutputStream “Pipe” (to another thread)
FilterOutputStream Decorators subclass this
class
Types of OutputStream Writes to:
27
• 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
c’s printf(). Converts arguments to ASCII or EBCDIC. Use
PrintWriter when writing Unicode characters rather than bytes.
• BufferedOutputStream – Adds a buffer (usually do this).
Three important FilterOutputStream classes -- Decorators
28
Writing ASCII Data To A FilePrintStream writes in the platform’s defaultencoding.
File Name
File Name
PrintStream
BufferedOutputStream
FileOutputStream
String Sink
Decorators
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("IODemo.out")));
out.println("Hello world...on a file");
out.close();
}
}
30
DataOutPutStream is for binary output.DataInputStream is for reading binary.
DataOutputStream
BufferedOutputStream
FileOutputStream
String Sink
Decorators
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); // can’t view this!! out.writeDouble(2.33); out.close(); }}
32
Readers and Writers
• New in Java 1.1• Provide Unicode-compliant, character-based I/O• Similar in structure to the InputStream and OutputStream “byte” hierarchy
33
PrintWriter has replaced PrintStream for text output.
PrintWriter
BufferedWriter
FileWriter
String Sink
Decorators
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();
}
}
35
Inputstream
InputStreamReader
BufferedReader
A System.in object is of type InputStream
Converting from an 8-bit InputStream to 16-bit Unicode
Converts from an InputStreamto a Reader
36
import 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);
}
}
37
BufferedReader
InputStreamReader
FileInputStream
String
InputStream
Reader
38
import java.io.*; // Read and write an ASCII filepublic 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); }}
39
Some 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(System.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
// <ctrl><z> 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);
}}
41
Some 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(System.in);
42
System.out.println("I'll echo and count lines");
int lineCount = 0;
int i;
i = is.read(); // -1 = EOF = <ctrl><z> in DOS
while(i != -1) {
char c = (char) i;
if(c == '\n') lineCount++;
System.out.print(c);
i = is.read();
}
System.out.println("--------------------------");
System.out.println("Line count == " + lineCount);
}
}
43
// 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
{
Some Examples Using StringTokenizer
44
InputStreamReader is = new InputStreamReader(System.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);
}
}
46
Some 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 absentimport 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
}}
47
// Java I/O// Read a double and display its square rootimport java.io.*;
public class DoubleIO { public static void main(String arg[]) throws IOException { InputStreamReader is = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(is);
Some Examples
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 < 0 System.out.println("The square root of "+x+" is " + Math.sqrt(x)); }}
49
Object 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”
50
Object serialization
• Class must implement Serializable
• Wrap a stream in a ObjectOutputStream (for writing) or ObjectInputStream (for reading)
• Use writeObject( ) and readObject( )
51
An Example Writing BigIntegers
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); }}
Use OutputStream NOT Writer
52
Another 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); }}
53
Some 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);
}}
55
C:\McCarthy\46935\io\Serialization>java SaveAListThe cat and the hat's hat cats[Little Cat C, Little Cat B, Little Cat A]
Output
56
• Historically error- prone, difficult, complex
• Threading is very useful and relatively
easy here
• Excellent reference: “Java Network
Programming” by Elliotte Rusty Harold,
O’Reilly Books, 1997.
I/O on the Net
Source: Eckel
57
• 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.getByName( ) produces a Java object containing address
Identifying a Machine
Source: Eckel
58
• 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
Servers & Clients
Source: Eckel
59
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 loopback:InetAddress.getByName("127.0.0.1");
• open two windows and talk
Testing w/ o a Network
60
• IP address isn’t 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.
Port: Unique “Place” in a Machine
61
• 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
Ports
62
• 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 isn’t 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
Sockets
63
Just 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, it’s like reading and writing any other IO stream!
64
// JabberServer. Java From Bruce Eckel’s 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 )
Some Examples Client/Server
65
try { 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 Eckel’s 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);
68
BufferedReader 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 < 10; i ++) { out. println(" howdy " + i); String str = in. readLine(); System. out. println( str); } out. println(" END"); } catch( Exception e) { e. printStackTrace(); } }}
70
Lab Problem Discussion
From “Just Java” page 378
Modify the program below (Dump.java) so that it alsooutputs 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 printableform, and print a “.” if it does not. This ensures that lines arethe 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.length==0) { System.out.println("usage: java Dump somefile"); System.exit(0); }
72
PrintStream e = System.err; try { myFIS = new FileInputStream( arg[0] ); myFOS = new FileOutputStream( arg[0] + ".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 " + arg[0]);
int i; while ( (i=myBIS.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() < 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) + " " ); } }