Outline Basic IO File class The Stream Zoo Serialization Regular Expressions.

Post on 18-Jan-2016

218 views 0 download

transcript

Outline

Basic IO File class The Stream Zoo Serialization Regular Expressions

Reading Text from the KeyboardPre-5.0

The infamous magic formula:

Difficult and confusing for new programmers, especially if reading numbers

BufferedReader stdin =

new BufferedReader(

new InputStreamReader(System.in));

String line = stdin.readLine();

Reading Text from a FilePre-5.0

To open and read a text file:

– Note that this code can throw IOExceptions (a checked exception)

BufferedReader in =

new BufferedReader(

new FileReader("novel.txt"));

String line;

while ((line = in.readLine())!= null)

System.out.println(line);

Reading from the KeyboardPost-5.0

Using the new Scanner class:

See the program InputTest.java on p. 59 Note that nextInt will leave white space in

the input buffer, so reading a line after reading a number can cause problems.

Scanner in = new Scanner(System.in);

String name = in.nextLine();

int age = in.nextInt();

Formatting OutputPost-5.0

Using the new printf method:

See the pages 61-64 in Core Java Formatting output in pre-5.0 Java is more

complicated.

String name;

int age;

System.out.printf("Hello, %s. Next year you'll be %d", name, age + 1);

Token Parsing Pre 1.4: Use StringTokenizer class Post 1.4: Use split method of String class

StringTokenizer doesn't allow "random access" like a string array does.

split parameter is a regular expression.

String str = "Groucho Harpo Chico";

String[] names = str.split("\\s");

The File Class Misleading name, should be called Path Use to:

– Get list of files in a directory

– See if a file exists

– Create, delete, and rename files Uses system-dependent information

– e.g., uses right kind of slash

The Input/Output FrameworkJava supports two types of IO: Stream IO

– A stream is a sequence of bytes. – Stream-based IO supports reading or writing data

sequentially. – A stream may be opened for reading or writing, but not

reading and writing. – There are two types of streams: the byte stream and the

character stream. Random access IO

– Random access IO support reading and writing data at any positions of a file. A random access file may be opened for reading and writing.

The Stream Zoo

More than 60 different stream classes Abstract base classes:

Input Output

Bytes InputStream OutputStream

Characters Reader Writer

Byte Streams

Character Streams

public class java.lang.System { public static final InputStream in; public static final PrintStream out; public static final PrintStream err; //...}

Standard Input/Output Streams

BufferedReader in = new BufferedReader( new FileReader("foo.in"));

BufferedReader in = new BufferedReader( new InputStreamReader(System.in));

PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter("foo.out")));

Writer out = new BufferedWriter( new OutputStreamWriter(System.out));

Using Reader and Writer

By default, the character encoding is specified by the system property:

file.encoding=8859_1

You can use other encoding by doing the following BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream("foo.in"), "GB2312"));

PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( new FileOutputStream("foo.out", "GB2312"))));

Character Encoding

Serialization

Useful for writing objects to a file or sending across network connection

Use ObjectOutputStream and ObjectInputStream

Declare that class implements Serializable interface– No methods in Serializable interface

Does not deal with static variables Uses reflection to determine structure of objects

Versions

Will not read in objects serialized with a different version of the class!

It is possible to indicate that older versions are compatible with the current version, but you must do some extra work.– See Versioning, pages 679-681

Uses the serialver program that comes with the JDK

Sample Code Fragment See ObjectFileTest.java (p. 663 in Core Java)

Employee[] staff = new Employee[3];

// ...INITIALIZE ARRAY...

ObjectOutputStream out = ...

out.writeObject(staff);

ObjectInputStream in = ...

Employee[] newStaff = (Employee[]) in.readObject();

Saving object references

Want to store and recover references

Don't want objects stored more than once

Give each object a serial number

If object has been stored already, refer to it by serial number

Employee

Harry HackerName

Manager

Tony TesterName

Secretary

Manager

Carl CrackerName

Secretary

See diagram on page 670 and ObjectRefTest.java on p. 672

Modified serialization

Some fields should not or can not be serialized:– file handles, handles of windows

– instances of classes that don't implement Serializable

Declare as transient– will be ignored during serialization

readObject and writeObject

Automatically called during serialization Can be used to write out transient data Take one parameter:

ObjectInputStream or ObjectOutputStream These methods are private and can only be

called by the serialization mechanism.

public class LabeledPoint implements Serializable {

...

private String label;

private transient Point2D.Double point;

}

Example

Point2D.Double is not serializable, so point is declared transient and will be ignored by default serialization procedure.

Core Java, p.677

private void writeObject(ObjectOutputStream out)

throws IOException {

out.defaultWriteObject();

out.writeDouble(point.getX());

out.writeDouble(point.getY());

}

private void readObject(ObjectInputStream in)

throws IOException {

in.defaultReadObject();

double x = in.readDouble();double x = in.readDouble();point = new Point2D.double(x, y);

}The order in which items are read must be the same as the order in which they are written, for obvious reasons.

The Externalizable interface

Has two methods:– readExternal and writeExternal

fully responsible for saving and restoring data, including superclass data

faster than serialization public methods, which might permit

modifications to an object

"New" I/O: java.nio

Supports the following features: Memory-mapped files

– uses virtual memory implementation to map a file into memory

– can improve performance File locking Character set encoders and decoders Nonblocking I/O

Regular expressions "Similar" to REs in Perl Pattern class

– matcher method returns a Matcher object Matcher provides various methods:

– find--returns true if another match is found

– group(int g)--returns the string matching group g

– lookingAt--returns true if beginning of input matches pattern

– replace and replaceAll

– reset

RE examples How would you describe this code?

Note that input can be an object of any class that implements CharSequence, including String, StringBuilder, or CharBuffer Also see HrefMatch.java, Core Java, p. 703-704

Example 12-10 v1/v1ch12/HrefMatchjava HrefMatch http://zephyr.uvsc.edu

Pattern pattern = Pattern.compile("[0-9]+");

Matcher matcher = pattern.matcher(input);

String output = matcher.replaceAll("#");