Download Notes From “Just Java”

Document related concepts
no text concepts found
Transcript
Week 2
•
•
•
“Just Java” by Linden chapters
4,5,13
Java I/O and Client/Server
Lab Problem
Some of the material on I/O and client/server is from Bruce
Eckel’s “Thinking in Java”
1
Notes From “Just Java”
Chapter 4
2
Comments
// a single line comment
/* a multi-line
comment
*/
/** a javadoc
comment
*/
javadoc MyDocumentedProgram.java produces .html files
3
Casts
// 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\Examples>java TestCast
-7616
4
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
5
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()
6
Notes From “Just Java”
Chapter 5
7
Forward References
// works fine
class Fruit {
void foo() { grams = 22; }
int grams;
}
8
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.
9
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 TestSheep
99
10
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 equal
precedence.
Order of operations is strictly left to right in Java.
11
Example
public 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
12
What 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.
13
Example
public class TestOverflow {
public static void main(String a[]) {
byte i = 8;
byte m = 0;
i = (byte) (i % m);
}
}
C:\McCarthy\www\JustJava\Examples>java TestOverflow
Exception in thread "main" java.lang.ArithmeticException: / by zero
14
at TestOverflow.main(TestOverflow.java:7)
Adding 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\Examples>java TestOverflow
}
That did not go well
15
Terminating
Notes From Bruce Eckel’s
Thinking in Java
“Just Java” Chapter 13
Simple I/O
16
JAVA I/O and
Client/Server
17
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
18
The 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
19
InputStream 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
20
Types of InputStream
ByteArrayInputStream
read memory block
StringBufferInputStream
buffer)
read from String (not
FileInputStream
read from file
PipedInputStream
thread
read from another
SequenceInputStream
streams
FilterInputStream
class.
reads from several
Decorators subclass this
21
A FilterInputStream contains some other input stream, which
Two 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
22
FileInputStream - Reading Data From a File
BufferedInputStream – Buffers input
DataInputStream – Reading binary data
readLine() -- deprecated
DataInputStream
BufferedInputStream
Decorators
FileInputStream
String
Source of data
File
Name
23
// 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])));
24
byte byteIn;
try {
while(true) {
byteIn = in.readByte();
out.writeByte(byteIn);
}
}
catch(EOFException e) {
in.close();
out.close();
}
}
}
25
Types of OutputStream
Writes to:
ByteArrayOutputStream
Block of memory
FileOutputStream
File
PipedOutputStream
thread)
“Pipe” (to another
FilterOutputStream
this
Decorators subclass
class
26
Three 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
c’s printf(). Converts arguments to ASCII or EBCDIC. Use
PrintWriter when writing Unicode characters rather than
bytes.
27
Writing ASCII Data To A File
PrintStream writes in the platform’s default
encoding.
PrintStream
BufferedOutputStream
Decorators
FileOutputStream
String
File
Name
Sink
28
// 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();
}
}
29
DataOutPutStream is for binary output.
DataInputStream is for reading binary.
DataOutputStream
BufferedOutputStream
Decorators
FileOutputStream
String
Sink
30
// 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();
}
}
31
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
32
PrintWriter has replaced PrintStream for
text output.
PrintWriter
BufferedWriter
Decorators
FileWriter
String
Sink
33
// 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();
}
}
34
Converting 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
35
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);
}
}
36
BufferedReader
InputStreamReader
Reader
FileInputStream
InputStream
String
37
import 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);
}
}
38
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");
39
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);
}}
40
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);
41
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);
}
}
42
Some 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
{
43
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");
44
int sum = 0;
while(st.hasMoreElements()) {
int val = Integer.parseInt(st.nextToken());
sum += val;
}
System.out.println("The sum is " + sum);
}
}
45
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 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
}
}
46
Some 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(System.in);
BufferedReader br = new BufferedReader(is);
47
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));
}
}
48
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”
49
Object serialization
• Class must implement Serializable
• Wrap a stream in a
ObjectOutputStream (for
writing)
or
ObjectInputStream (for reading)
• Use writeObject( ) and
readObject( )
50
An 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);
}
}
51
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);
}
52
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");
53
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);
}
}
54
Output
C:\McCarthy\46935\io\Serialization>java SaveAList
The cat and the hat's hat cats[Little Cat C, Little Cat B, Little Cat A]
55
I/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,
O’Reilly Books, 1997.
Source: Eckel
56
Identifying 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.getByName( ) produces
Source: Eckel
a
57
Servers & 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
58
Testing 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
loopback:InetAddress.getByName("127.0.0.1");
• open two windows and talk
59
Port: Unique “Place” in a Machine
• IP address isn’t enough to identify a unique
server
• Many servers can exist on one machine
Protocol
http server
ftp server
telnet
finger
Port
80
21
23
79
• A “server” is a program watching a port.
60
Ports
• 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
61
Sockets
• 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
62
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!
63
Some Examples
Client/Server
// 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 )
64
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);
65
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();
}
}
66
// 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);
67
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
// Enable PrintWriter autoflush:
PrintWriter out = new PrintWriter( new
BufferedWriter(
new OutputStreamWriter(
socket. getOutputStream())),
flush);
68
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();
}
}
}
69
Week 2 Lab Problem
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”.
70
// 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);
}
71
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 );
}
72
} 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 + ":" );
}
73
// 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) + " " );
}
}
74