260 likes | 383 Vues
This guide provides an in-depth exploration of Java I/O, covering the use of directory listings, streams, decorators, readers and writers, tokenizers, and object serialization. Learn how to manipulate files and directories, handle input and output efficiently, and utilize various stream types. The document discusses the decorator pattern for filtering streams, the differences between streams and readers/writers, and the process of object serialization. Discover best practices for file handling, data compression, and the new I/O features introduced in Java.
E N D
What We Will Learn • Using directory listings • Using Streams • Decorators • Readers and Writers • Tokenizers • New I/O * • Compression * • Object Serialization
Files and Directories • File class in java.io package • Represents name of a file or a set of files • You cannot read or write data using File • Used for • Manipulating filenames • Working with directories • Checking file attributes
Input and Output • Looking into input and output in an abstract way • Input: • Reading data from a source • Source: anything that we can read data items from it • Output: • Writing data to a sink • Sink: anything that we can write data items to it
Streams • Abstract class representing a data source/sink • InputStream: • Represents a source • Provides read() methods • OutputStream: • Represent a sink • Provides write() methods
Kinds of Streams • Streams are categorized according to type of source or sink they represent • Files • Arrays of bytes • Strings • Pipes • Internet connections
InputStream Example publicvoidecho(InputStreamin) throwsIOException { intb; while ((b = in.read()) != -1) System.out.print((char)b); } • Using echo: • echo(System.in) • echo(new FileInputStream("test.txt")) • It works for any kind of input stream
Input Stream Classes • ByteArrayInputStream • Arrays of bytes • FileInputStream • Files • StringBufferInputStream • Strings • ObjectInputStream • Serialized objects
Adding Features • Adding various features to streams such as: • Compression • Line-numbering • Buffering • Push-back • Combining these features with every stream causes inheritance tree explosion! • CompressedFileInputStream • BufferedFileInputStream • CompressedBufferedFileInputStream, ...
Filter Streams • Wrap around other streams • Adding features to them • Without changing the interface • Such as: • BufferedInputStream • LineNumberInputStream • PushbackInputStream • DataInputStream • ZipInputStream
Filter Example • We want to read • from a file • which is compressed • with buffering mechanism • with ability to pushback data into it • We use one filter for each
Pushback I S Zip I S close Buffered I S close read File I S read close close read read Filter Example
Using Filters PushbackInputStreamin = newPushbackInputStream( newZipInputStream( newBufferedInputStream( newFileInputStream("in.dat")))); echo(in); in.pushback(89); in.close(); • After construction, in can be used as an ordinary input stream • Additional methods for pushback is available
Decorator Pattern • All filters are subclasses of FilterInputStream • Which is a InputStream itself • Takes an InputStream upon construction • And filters data going through it • The interface is not changed • Since the filter is also an Input Stream • This way to define classes to add features is called the Decorator pattern
Readers and Writers • A separate hierarchy but pretty similar to streams • Added from Java 1.1 to handle Unicode IO • Reader is similar to InputStream • Writer is similar to OutputStream • Similar usage of filters
Readers Example publicvoidechoLn(Readerin) throwsIOException { LineNumberReaderst = newLineNumberReader(in); Stringline; while ((line = st.readLine()) != null) System.out.println(st.getLineNumber() + ":" + line); } • Using echoLn: • echoLn(new FileReader("in.txt"));
Streams to Readers Readerr = newInputStreamReader(System.in); echoLn(r); • To read from a stream as a reader, use InputStreamReader • OutputStreamWriter is used for output • Reverse conversion is invalid
Formatted Input • Is not easy! • One way is to read lines and then parse items • Using tokenizers is another way • StringTokenizer: breaking strings into tokens • StreamTokenizer: reads from a stream or reader token by token
StreamTokenizer • Can be used as a scanner • Set of configurable items: • whitespaces, punctuations, comment characters • Can recognize • ordinary tokens • numbers • quoted strings • comments
New I/O • Added in JDK 1.4 • Has one goal: speed • You benefit from its speed • When writing code using nio • When using “old” I/O packages (because they have been reimplemented using nio) • You should read TIJ and learn nio yourselves!!!!!!
Compression • Java I/O has classes that support compression • You should read TIJ and learn compression yourselves!!!!!!
Object Serialization • Turning an object into a sequence of bytes • The object should implement the Serializable interface • Serializable is a tagging interface and has no methods • Is platform independent
Object Serialization • Lightweight persistence • For more sophisticated persistence mechanism consider JDO or a tool like Hibernate
Object Serialization Worm w = new Worm(); // a serializable obj ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("worm.out")); out.writeObject("Worm storage\n"); out.writeObject(w); out.close(); // Also flushes output
Object Serialization • A clever aspect of Java serialization is that when you save an object, it find all the objects referenced in that object and save those. • This process is performed recursively and a “web of objects” is saved.
Object Serialization ObjectInputStream in = new ObjectInputStream( new FileInputStream(new File("..", "X.file"))); Object mystery = in.readObject();
Object Serialization • The transient keyword • You can control serialization by implementing Externalizableinstead of serializable