+ All Categories
Home > Documents > Outline Basic IO File class The Stream Zoo Serialization Regular Expressions.

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

Date post: 18-Jan-2016
Category:
Upload: poppy-dean
View: 218 times
Download: 0 times
Share this document with a friend
26
Outline Basic IO File class The Stream Zoo Serialization Regular Expressions
Transcript
Page 1: Outline  Basic IO  File class  The Stream Zoo  Serialization  Regular Expressions.

Outline

Basic IO File class The Stream Zoo Serialization Regular Expressions

Page 2: 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();

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

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);

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

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();

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

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);

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

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");

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

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

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

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.

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

The Stream Zoo

More than 60 different stream classes Abstract base classes:

Input Output

Bytes InputStream OutputStream

Characters Reader Writer

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

Byte Streams

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

Character Streams

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

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

Standard Input/Output Streams

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

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

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

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

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

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

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

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

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

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();

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

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

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

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

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

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.

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

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

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

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.

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

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

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

"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

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

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

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

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("#");


Recommended