ObjectOriented Design and Programming Java Topics Covered Today
Object-Oriented Design and Programming (Java)
Topics Covered Today • 3. 1 Input and Output Programming – 3. 1. 0 Java I/O Stream – 3. 1. 1 File I/O – 3. 1. 2 Using File I/O in the Library System 2
Java I/O Stream • • • What is an I/O stream? Types of Streams Stream class hierarchy Control flow of an I/O operation using Streams Byte streams Character streams Buffered streams Standard I/O streams Data streams Object streams File class 3
What is an I/O Stream? • An I/O Stream represents an input source or an output destination • A stream can represent many different kinds of sources and destinations – disk files, devices, other programs, a network socket, and memory arrays • Streams support many different kinds of data – simple bytes, primitive data types, localized characters, and objects 4
I/O Streams • No matter how they work internally, all streams present the same simple model to programs that use them – A stream is a sequence of data 5
Input Stream • A program uses an input stream to read data from a source (a file, memory, a socket), and reads the information sequentially, one item at a time. 6
Output Stream • A program uses an output stream to write data to a destination, and writing the information out sequentially, one item at time. 7
Types of Streams • General Stream Types – Character and Byte Streams • Character vs. Byte – Input and Output Streams • Based on source or destination – Node and Filter Streams • Whether the data on a stream is manipulated or transformed or not 8
Character and Byte Streams • Byte streams – For binary data – Root classes for byte streams: • The Input. Stream Class • The Output. Stream Class • Both classes are abstract – Classes of Byte Streams • • Input. Stream、Output. Stream File. Input. Stream、File. Output. Stream Piped. Input. Stream、Piped. Output. Stream Byte. Array. Input. Stream、Byte. Array. Output. Stream Filter. Input. Stream、Filter. Output. Stream Data. Input. Stream、Data. Output. Stream Buffered. Input. Stream、Buffered. Output. Stream 9
Character and Byte Streams • Character Streams – For Unicode characters – Root classes for character streams • The Reader class • The Writer class • Both classes are abstract – Most programs should use readers and writers to read and write textual information. • • Reader、Writer Input. Stream. Reader、Output. Stream. Writer File. Reader、File. Writer Char. Array. Reader、Char. Array. Writer Piped. Reader、Piped. Writer Filter. Reader、Filter. Writer Buffered. Reader、Buffered. Writer String. Reader、String. Writer 10
Input and Output Streams • Input or source streams – Can read from these streams – Root classes of all input streams: • The Input. Stream Class • The Reader Class • Output or sink (destination) streams – Can write to these streams – Root classes of all output streams: • The Output. Stream Class • The Writer Class 11
Node and Filter Streams • Node streams (Data sink stream) – Contain the basic functionality of reading or writing from a specific location – Types of node streams include files, memory and pipes • Filter streams (Processing stream) – Layered onto node streams between threads or processes – For additional functionality- altering or managing data in the stream • Adding layers to a node stream is called stream chaining (stream链) 12
java. io hierarchies 13
Abstract Classes • Input. Stream & Output. Stream • Reader & Writer 14
Input. Stream Abstract Class • Read data from Input. Stream: – int read( ); Reads the next byte of data from the input stream – int read( byte b[ ] ); Reads some number of bytes from the input stream and stores them into the buffer array b. – int read( byte b[ ], int off, int len ); Reads up to len bytes of data from the input stream into an array of bytes. – int available( ); Returns the number of bytes that can be read • Close Stream: – close( ); Closes this input stream and releases any system resources associated with the stream. 15
Input. Stream Abstract Class 16
Node Input. Stream Classes 17
Filter Input. Stream Classes 18
Output. Stream Abstract Class • Write data: – void write( int b ); Writes the specified byte to this output stream. – void write( byte b[ ] ); Writes b. length bytes from the specified byte array to this output stream – void write( byte b[ ], int off, int len ); Writes len bytes from the specified byte array starting at offset off to this output stream. • Close stream: – close( ); • Buffer flush: – flush( ); Flushes this output stream and forces any buffered output bytes to be written out. 19
Node Output. Stream Classes 20
Filter Output. Stream Classes 21
The Reader Class • Read character(s) – public int read() throws IOException; – public int read(char cbuf[]) throws IOException; – public abstract int read(char cbuf[], int off, int len) throws IOException; • Close reader – public abstract void close() throws IOException; 22
The Reader Class 23
Node Reader Classes 24
Filter Reader Classes 25
The Writer Class • Write character(s) to output stream – public void write(int c) throws IOException; – public void write(char cbuf[]) throws IOException; – public abstract void write(char cbuf[], int off, int len) throws IOException; – public void write(String str, int off, int len) throws IOException; • Flush – flush( ) • Close stream – public abstract void close() throws IOException; 26
Node Writer Classes 27
Filter Writer Classes 28
Control Flow of an I/O operation Reading 1. Create a stream object and associate it with a data-source 2. Give the stream object the desired functionality through stream chaining Writing 1. Create a stream object and associate it with a data-destination 2. Give the stream object the desired functionality through stream chaining 3. while (there is more information) 4. read next data from the stream 4. write next data to the stream 5. close the stream 29
Byte Stream • Programs use byte streams to perform input and output of 8 -bit bytes • All byte stream classes are descended from Input. Stream and Output. Stream • There are many byte stream classes – File. Input. Stream and File. Output. Stream 30
When Not to Use Byte Streams? • Byte Stream represents a kind of low-level I/O that you should avoid – If the data contains character data, the best approach is to use character streams – There also streams for more complicated data types • Byte streams should only be used for the most primitive I/O • All other streams are based on byte stream 31
Example: File. Input. Stream & File. Output. Stream 32
Example: File. Input. Stream & File. Output. Stream 33
Character Stream • The Java platform stores character values using Unicode conventions • Character stream I/O automatically translates this internal format to and from the local character set. – In Western locales, the local character set is usually an 8 -bit superset of ASCII. • All character stream classes are descended from Reader and Writer • As with byte streams, there are character stream classes that specialize in file I/O: File. Reader and File. Writer. 34
Example: File. Reader & File. Writer 35
Example: File. Reader & File. Writer 36
Input. Stream. Reader & Output. Stream. Writer • public Input. Stream. Reader(Input. Stream in); – processing stream – reads bytes from an Input. Stream and converts them to characte • public Input. Stream. Reader(Input. Stream in, String enc) throws Unsupported. Encoding. Exception; – charset decoder – ISO 8859 -1,UTF-8,UTF-16 • public Output. Stream. Writer(Output. Stream out); – Processing stream – converts characters to bytes • public Output. Stream. Writer(Output. Stream out, String enc) throws Unsupported. Encoding. Exception; 37
Line-oriented I/O 38
Buffered Stream • Why Buffered Streams? – An unbuffered I/O means each read or write request is handled directly by the underlying OS • This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive. – To reduce this kind of overhead, the Java platform implements buffered I/O streams • Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty • Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full. 39
How to create Buffered Streams? • A program can convert a unbuffered stream into a buffered stream using the wrapping idiom – A unbuffered stream object is passed to the constructor for a buffered stream class – Example input. Stream = new Buffered. Reader( new File. Reader("xanadu. txt")); output. Stream = new Buffered. Writer( new File. Writer("characteroutput. txt")); 40
Buffered Stream Classes • Buffered. Input. Stream and Buffered. Output. Stream create buffered byte streams • Buffered. Reader and Buffered. Writer create buffered character streams 41
Flushing Buffered Streams • It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is known as flushing the buffer. • Some buffered output classes support autoflush, specified by an optional constructor argument. – When autoflush is enabled, certain key events cause the buffer to be flushed – For example, an autoflush Print. Writer object flushes the buffer on every invocation of println or format. • To flush a stream manually, invoke its flush method – The flush method is valid on any output stream, but has no effect unless the stream is buffered. 42
Buffered. Reader & Buffered. Writer • Create buffered stream – – public Buffered. Reader(Reader in); use the default buffer size public Buffered. Reader(Reader in, int sz); public Buffered. Writer(Writer out); public Buffered. Writer(Writer out, int sz); • Buffered. Reader – public String read. Line() throws IOException; Read a line of text • Buffered. Writer – public void new. Line() throws IOException; Write a line separator. 43
Standard Streams on Java Platform • Three standard streams – Standard Input, accessed through System. in – Standard Output, accessed through System. out – Standard Error, accessed through System. err • These objects are defined automatically and do not need to be opened • System. out and System. err are defined as Print. Stream objects 44
Data Streams • Data streams support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values • All data streams implement either the Data. Input interface or the Data. Output interface • Data. Input. Stream and Data. Output. Stream are most widelyused implementations of these interfaces 45
Data. Output. Stream • Data. Output. Stream can only be created as a wrapper for an existing byte stream object 46
Data. Input. Stream • Like Data. Output. Stream, Data. Input. Stream must be constructed as a wrapper for a byte stream • End-of-file condition is detected by catching EOFException, instead of testing for an invalid return value 47
Object Streams • Object streams support I/O of objects – Like Data streams support I/O of primitive data types – The object has to be Serializable type • The object stream classes are Object. Input. Stream and Object. Output. Stream – These classes implement Object. Input and Object. Output, which are subinterfaces of Data. Input and Data. Output – An object stream can contain a mixture of primitive and object values 48
Input and Output of Complex Object • The write. Object and read. Object methods are simple to use, but they contain some very sophisticated object management logic – This isn't important for a class like Calendar, which just encapsulates primitive values. But many object contain references to other objects. • If read. Object is to reconstitute an object from a stream, it has to be able to reconstitute all of the objects the original object referred to. – These additional objects might have their own references, and so on. 49
Write. Object • The write. Object traverses the entire web of object references and writes all objects in that web onto the stream – A single invocation of write. Object can cause a large number of objects to be written to the stream. 50
I/O of multiple referred-to objects • Object a contains references to objects b and c, while b contains references to d and e 51
Close Streams • Always Close Streams – Closing a stream when it's no longer needed is very important — so important that your program should use a finally block to guarantee that both streams will be closed even if an error occurs – This practice helps avoid serious resource leaks. 52
Example: Closing File Buffered. Reader file. In = new Buffered. Reader(new File. Reader(filename)); Print. Writer file. Out = new Print. Writer(new File. Writer(filename)); . . . file. In. close(); file. Out. close(); 53
Topics Covered Today • 3. 1 Input and Output Programming – 3. 1. 0 Java I/O Stream – 3. 1. 1 File I/O – 3. 1. 2 Using File I/O in the Library System 54
The java. io. File Class • Either a directory or a file • Constructor: – File(String pathname) – File(File parent, String child) – File(String parent, String child) • File does not read and write, streams will handle the read or write from/to a file. 55
Create java. io. File Class • File(String pathname) File f 1 = new File("d: /ssd 3/unit 3/Dir. List/. "); File f 2 = new File(". "); • File(File parent, String child) • File(String parent, String child) File Dir = new File(“d: \ssd 3"); File Full. Filename = new File(Dir, "File. Demo. raw "); 56
Listing Files import java. io. *; import java. util. *; public class Dir. List { public static void main(String[] args) { File path = new File(". "); String[] list; System. out. println(path. get. Absolute. Path()); list = path. list(); for (int i = 0; i < list. length; i++) System. out. println(list[i]); } } 57
Other File Methods • • can. Read() can. Write() exists() get. Parent() is. Directory() is. File() last. Modified() length() 58
File Methods for Modifying • • create. New. File() delete() make. Dirs() rename. To() set. Last. Modified() set. Read. Only() 59
File. Input. Stream • Create a File. Input. Stream – public File. Input. Stream(String name) – public File. Input. Stream(File file) • File. Not. Found. Exception is thrown if – the named file does not exist, – it is a directory rather than a regular file, – for some other reason cannot be opened for reading • Closes this file input stream and releases any system resources associated with the stream 60
File. Input. Stream Example import java. io. *; class Main. Class { public static void main(String args[])throws Exception{ // 1. Create File object File. Input. Stream in. File=new File. Input. Stream("c: \test. txt"); // 2. Create Reader Object to read the text Buffered. Reader reader=new Buffered. Reader( new Input. Stream. Reader(in. File)); // 3. Read data String str. Line; while((str. Line=reader. read. Line())!=null) System. out. println(str. Line); reader. close(); in. File. close(); } } 61
File. Output. Stream • Create File Object java. io. File file = new java. io. File("C: \test. txt"); • Create File. Output. Stream java. io. Output. Stream os = new java. io. File. Output. Stream(file); • Write data – os. write(byte [ ] b) 62
File. Output. Stream Example byte[] Data = new byte[100]; java. io. File file = new java. io. File("C: \test. txt "); try{ java. io. Output. Stream os = new File. Output. Stream(file); try { os. write(Data); } catch(java. io. IOException e) { } } catch (java. io. File. Not. Found e) { } 63
File. Reader • File. Reader(File file) • File. Reader(String file. Name) // 1. Create Reader Object to read the text Buffered. Reader reader = new Buffered. Reader( new File. Reader("c: \test 2. txt")); // 2. Read data line by line String str. Line; while((str. Line = reader. read. Line()) != null) System. out. println(str. Line); reader. close(); 64
File. Writer • Again, basically the same. The constructors are – File. Writer(File file) – File. Writer(String file. Name, boolean append) • The last one allows appending, rather than writing to the beginning (and erasing an existing file!). • These will create files! 65
File I/O Example • Program description: – It first prompts the user for two file names, the name of an input file and the name of an output file, and then copies the contents of the input file to the output file. 66
Copy. File. java import java. io. *; public class Copy. File { private static Buffered. Reader std. In = new Buffered. Reader( new Input. Stream. Reader(System. in)); private static Print. Writer std. Out = new Print. Writer( System. out, true); private static Print. Writer std. Err = new Print. Writer(System. err, true); 67
Copy. File. java public static void main(String[] args) throws IOException { std. Err. print("Source filename: "); std. Err. flush(); Buffered. Reader input = new Buffered. Reader( new File. Reader(std. In. read. Line())); std. Err. print("Destination filename: "); std. Err. flush(); Print. Writer output = new Print. Writer(new File. Writer(std. In. read. Line())); String line = input. read. Line(); while (line != null) { output. println(line); line = input. read. Line(); } input. close(); output. close(); std. Out. println("done"); }} 68
Random-Access file • Random. Access. File allow you to read/write data beginning at the a specified location – a file pointer is used to guide the starting position – it supports both input and output with both bytes and characters • Methods of Interface Data. Input: – read. Boolean( ) – read. Int( ) – read. Line( ) • Method of Interface Data. Output: – write. Char( ) – write. Double( ) 69
Using a Random Access File import java. io. *; public class RAFDemo { public static void main(String[] args) { try { File f = new File(“filename"); Random. Access. File raf = new Random. Access. File(f, "rw"); // Read a character char ch = raf. read. Char(); // Seek to end of file raf. seek(f. length()); // Append to the end raf. write. Chars("a. String"); raf. close(); } catch (IOException e) { } } } 70
File Stream • The file streams read or write from a file on the native file system • File Streams – File. Reader – File. Writer – File. Input. Stream – File. Output. Stream 71
Topics Covered Today • 3. 1 Input and Output Programming – 3. 1. 0 Java I/O Stream – 3. 1. 1 File I/O – 3. 1. 2 Using File I/O in the Library System 72
Add More Features • The data for the library catalog will be stored in a data file and the library system will load the catalog from that file. – catalog. dat • The data formats are: – Book_code_title_year_author_number. Of. Pages – Recording_code_title_year_performer_format • Borrower data will be write to a file in one of three formats: Plain text, HTML and XML. 73
UML class diagram 74
Interface Library. Catalog. Loader /** * This interface declares a method for obtaining a library catalog * from a file. */ public interface Library. Catalog. Loader { /** * Loads the information in the specified file into a library * catalog and returns the catalog. * * @param filename the name of the file that contains the catalog data. * @return a {@link Catalog}. * @throws File. Not. Found. Exception if the specified file does not exist. * @throws IOException if there is an error reading the * information in the specified file. * @throws Data. Format. Exception if the file contains malformed data. */ Catalog load. Catalog(String filename) throws IOException, File. Not. Found. Exception, Data. Format. Exception; } 75
Class File. Library. Catalog. Loader import java. util. *; import java. io. *; /** * Creates a library catalog and loads it with data stored in a file. * * @see Catalog. Item * @see Recording * @see Book */ public class File. Library. Catalog. Loader implements Library. Catalog. Loader { /* Prefix of a line with book data */ private final static String BOOK_PREFIX = "Book"; /* Prefix of a line with recording data */ private final static String RECORDING_PREFIX = "Recording"; /* Delimiter */ private final static String DELIM = "_"; 76
Class File. Library. Catalog. Loader /** * Loads the information in the specified file into a library catalog and returns the catalog. * @param filename The name of a file that contains catalog information. * @return a library catalog. * @throws File. Not. Found. Exception if the specified file does not exist. * @throws IOException if there is an error reading the information in the specified file. * @throws Data. Format. Exception if the file contains malformed data. */ public Catalog load. Catalog (String filename) throws IOException, File. Not. Found. Exception, Data. Format. Exception { Catalog catalog = new Catalog(); Buffered. Reader reader = new Buffered. Reader(new File. Reader(filename)); String line = reader. read. Line(); while (line != null) { Catalog. Item item = null; if (line. starts. With(BOOK_PREFIX)) { item = read. Book(line); } else if (line. starts. With(RECORDING_PREFIX)) { item = read. Recording(line); } else { throw new Data. Format. Exception(line); } catalog. add. Item(item); line = reader. read. Line(); } return catalog; 77 }
Class File. Library. Catalog. Loader /** * Extracts the book data in the specified line and returns * a {@link Book} object that encapsulates the book data. * * @param line a string that contains book data. * @return a <code>Book</code> object that encapsulates the * book data in the specified line. * @throws Data. Format. Exception if the line contains errors. */ private Book read. Book (String line) throws Data. Format. Exception { String. Tokenizer tokenizer = new String. Tokenizer(line, DELIM); if (tokenizer. count. Tokens() != 6) { throw new Data. Format. Exception(line); } else { try { String prefix = tokenizer. next. Token(); return new Book (tokenizer. next. Token(), Integer. parse. Int(tokenizer. next. Token()), tokenizer. next. Token(), Integer. parse. Int(tokenizer. next. Token())); } catch (Number. Format. Exception nfe) { throw new Data. Format. Exception(line); } }} 78
Class File. Library. Catalog. Loader /** * Extracts the recording data in the specified line and returns * a {@link Recording} object that encapsulates the book data. * * @param line a string that contains recording data. * @return a <code>Recording</code> object that encapsulates the * recording data in the specified line. * @throws Data. Format. Exception if the line contains errors. */ private Recording read. Recording (String line) throws Data. Format. Exception { String. Tokenizer tokenizer = new String. Tokenizer(line, DELIM); if (tokenizer. count. Tokens() != 6) { throw new Data. Format. Exception(line); } else { try { String prefix = tokenizer. next. Token(); return new Recording (tokenizer. next. Token(), Integer. parse. Int( tokenizer. next. Token()), tokenizer. next. Token()); } catch (Number. Format. Exception nfe) { throw new Data. Format. Exception(line); } 79
Class Data. Format. Exception /** * This exception is thrown when malformed data is detected while * a file being parsed. */ public class Data. Format. Exception extends Exception { /** * Constructs a <code>Data. Format. Exception</code> with no detail message. */ public Data. Format. Exception() { } /** * Constructs a <code>Data. Format. Exception</code> with the * specified detail message. * * @param message the malformed data */ public Data. Format. Exception(String message) { super(message); } } 80
Writing Data to a File • Library. System. java 81
Complete Library System • The following files implement this version of the library system: – – – Book. java Recording. java Catalog. Item. java Catalog. java Borrower. java Borrowed. Items. java Borrower. Database. java Borrowers. Formatter. java Plain. Text. Borrowers. Formatter. java HTMLBorrowers. Formatter. java XMLBorrowers. Formatter. java 82
- Slides: 82