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

Slides:



Advertisements
Similar presentations
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. 2 Operating System Application #1 Application #2 Java Virtual Machine #1 Local Memory Shared Memory Threads.
Advertisements

I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Slide 10.1 Advanced Programming 2004, based on LY Stefanus’s Slides Object Serialization Object serialization: the process of converting an object into.
COMP201 Java Programming Topic 5: Input and Output Reading: Chapter 12.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
Lecture 7 File I/O (and a little bit about exceptions)‏
File I/O in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Advanced Java Class Serialization. Serialization – what and why? What? –Translating the contents of an Object to a series of bytes that represent it,
Chapter 91 Streams and File I/O Chapter 9. 2 Reminders Project 6 released: due Nov 10:30 pm Project 4 regrades due by midnight tonight Discussion.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
COMP201 Java Programming Topic 6: Streams and Files Reading: Chapter 12.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Chapter 20 – Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
Files and Streams (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) –it acts as.
Input / Output Chapter 13.  We use files all the time  Programs are files  Documents are files  We want them to be “permanent”  To last beyond execution.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
JAVA I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
Object Persistence and Object serialization CSNB534 Asma Shakil.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
Input/output Input in java is stream based.A stream represents sequence of bytes or characters. Stream provides an abstract view of I/O. Stream can be.
Two Ways to Store Data in a File  Text format  Binary format.
© Amir Kirsh Files and Streams in Java Written by Amir Kirsh.
CIS 270—App Dev II Big Java Chapter 19 Files and Streams.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
1 Software 1 Java I/O. 2 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
1 CISC 370: I/O Streams James Atlas June 24, 2008.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from.
– Advanced Programming P ROGRAMMING IN Lecture 22 Input and Output System.
©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
 Learn about computer files  Use the Path class  Learn about  Streams  Buffers  file organization  Use Java’s IO classes to write to and read from.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 20.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Files and Serialization. Files Used to transfer data to and from secondary storage.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
Java Input / Output l a modular approach to input/output: - different stream objects are connected/wrapped to handle I/O l a data stream object: a flow.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
1 CSE 331 Memento Pattern and Serialization slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
Object Writing in files
Program Input/Output (I/O)
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
I/O Streams- Basics Byte Streams and Character Streams
CSE 331 Memento Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
Presentation transcript:

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

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

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

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

Formatting Output Post-5.0  Using the new printf method:  See the pages 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 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.

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

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  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 Hacker Name Manager Tony Tester Name Secretary Manager Carl Cracker Name 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(); 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 Example v1/v1ch12/HrefMatch java HrefMatch Pattern pattern = Pattern.compile("[0-9]+"); Matcher matcher = pattern.matcher(input); String output = matcher.replaceAll("#");