Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Outline  Basic IO  File class  The Stream Zoo  Serialization  Regular Expressions."— Presentation transcript:

1 Outline  Basic IO  File class  The Stream Zoo  Serialization  Regular Expressions

2 Reading Text from the Keyboard Pre-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();

3 Reading Text from a File Pre-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);

4 Reading from the Keyboard Post-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();

5 Formatting Output Post-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);

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

7 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

8 The Input/Output Framework Java 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.

9 The Stream Zoo  More than 60 different stream classes  Abstract base classes: InputOutput BytesInputStreamOutputStream CharactersReaderWriter

10 Byte Streams

11 Character Streams

12 public class java.lang.System { public static final InputStream in; public static final PrintStream out; public static final PrintStream err; //... } Standard Input/Output Streams

13 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

14 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

15 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

16 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

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

18 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 Hacker Name Manager Tony Tester Name Secretary Manager Carl Cracker Name Secretary See diagram on page 670 and ObjectRefTest.java on p. 672

19 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

20 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.

21 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

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

23 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

24 "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

25 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

26 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/HrefMatch java HrefMatch http://zephyr.uvsc.edu Pattern pattern = Pattern.compile("[0-9]+"); Matcher matcher = pattern.matcher(input); String output = matcher.replaceAll("#");


Download ppt "Outline  Basic IO  File class  The Stream Zoo  Serialization  Regular Expressions."

Similar presentations


Ads by Google