Download presentation
Presentation is loading. Please wait.
Published byMatti Hyttinen Modified over 6 years ago
1
Stream Oriented I/O Computer Programming II Dr. Tim Margush
1/1/2019 Stream Oriented I/O Computer Programming II Dr. Tim Margush Mathematics, Science and Technology Department Farquhar Center - Nova Southeastern University
2
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
1/1/2019 Streams Character Stream A sequence of Unicode characters Unicode is automatically converted to and from the local host representation Byte Stream A sequence of Byte values No translation Binary mode Stream oriented I/O allows the programmer to treat all I/O in the same way. The characteristics of the physical device are hidden from the basic I/O operations. An input stream is a sequence of characters or bytes coming from a device to memory used by the program. An output stream is going to a device. Character streams automatically handle the conversions to and from unicode if the host system does not use unicode as its normal character code. Binary transfer of data is accomplished with a Byte stream. January 19 Nova Southeastern University Copyright Dr. Tim Margush
3
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
1/1/2019 java.io Classes File A file or directory OutputStream, InputStream Base class for Byte streams Writer, Reader Base class for Character streams RandomAccessFile The java.io package contains these five main classes related to stream I/O. These are all subclasses of Object. All are Abstract classes. They basically define the operations that will be available for these types of streams. A File object represents a file to be used for input or output. It can also represent a directory. The other classes represent streams. Files created as random access files are inherently the same as those created serially. The class used to access the data is all that changes. January 19 Nova Southeastern University Copyright Dr. Tim Margush
4
Sources, Sinks, and Filters
1/1/2019 Sources, Sinks, and Filters A class representing a source or destination (sink) for a stream of information is called a data stream class Files, Strings, network connections A class representing a manipulation or processing of a stream is called a filtered stream class January 19 Nova Southeastern University Copyright Dr. Tim Margush
5
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
1/1/2019 IOException Most IO operations are capable of throwing a checked exception derived from IOException Methods using these methods must either catch these exceptions, or be declared as capable of throwing them January 19 Nova Southeastern University Copyright Dr. Tim Margush
6
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
1/1/2019 Standard I/O Streams The System class manages resources of the executing program and contains these three public static objects associated with input and output operations System.in - an InputStream object generally attached to the keyboard System.out - a PrintStream object generally the display console System.err - similar to System.out These objects represent a source or sink that has already been "wrapped" as a stream object. In many cases, you will need to wrap it further to achieve enhanced functionality. January 19 Nova Southeastern University Copyright Dr. Tim Margush
7
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
1/1/2019 The File Class Constructors File(String fileOrPathName); File(File directory, String fileName); File(String directory, String fileName); Once a File object is created, information may be obtained from the various methods This is more than a simple file… it may also represent a collection of files or a directory. January 19 Nova Southeastern University Copyright Dr. Tim Margush
8
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
1/1/2019 Selected File Methods Boolean functions exists() isDirectory() isFile() canRead() canWrite() equals(File) String getName() String getPath() String[] list() returns an array of filenames if the object represents a directory long length() number of bytes in the file The equals() method only tells if two File objects refer to the same file. In some circumstances, a security exception is thrown when you invoke canRead or canWrite. The getName method returns the file name without the path or the directory name. getPath returns a String that includes the entire path and file or directory name. The list method is useful only when the File object is a directory. Otherwise it returns null. It is possible to specify a Filter when calling the list method: list(FilenameFilter); To use this, you pass an object that implements the FilenameFilter interface. This object will contain an accept method that returns true or false for a file passed as an argument. The files returned by list are those accepted by the filter. January 19 Nova Southeastern University Copyright Dr. Tim Margush
9
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
1/1/2019 File Modifications delete() deletes the file represented by the current File object renameTo(FilePath); renames and possibly moves the file named by the current object mkdir() and mkdirs() creates a directory (perhaps a whole path) named by the current object These methods return true if the operation is successful. The delete method will not delete directories, only files. The renameTo method can move a file if the FilePath specifies a file in another directory. The method fails if the target directory does not exist. After renaming, the current File object will refer to a non-existent file. mkdir will create a directory at the end of a path if the path already exists. It can add only one level to the directory tree. mkdirs, on the other had, can create an entire path if necessary. January 19 Nova Southeastern University Copyright Dr. Tim Margush
10
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
1/1/2019 Input Streams A collection of classes parallel the Output stream classes, beginning with InputStream at the top of the hierarchy FileInputStream SequenceInputStream PipedInputStream ByteArrayInputStream FilterInputStream ObjectInputStream InputStream's produce input from an array of bytes a String a file a "pipe" another stream some other connection – such as a connection to another computer via the Internet FileInputStream is constructed from a File object, or a String specifying the file to be attached to the Stream. FileNotFoundException may be thrown. This class provides support for input of bytes. Several input streams may be concatenated so the stream appears to come from one continuous source. The constructor allows you to specify the sequence of files to be combined. As each part of the stream is exhausted, it is automatically closed. A PipedInputStream is the other end of a PipedOutputStream. A ByteArrayInputStream reads bytes from a byte array in memory. The ObjectInputStream is designed for reading into objects from files created expressly for this purpose through Serialization. FilterInputStream provides additional classes for wrapping on these basic ones. January 19 Nova Southeastern University Copyright Dr. Tim Margush
11
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
1/1/2019 FilterInputStream DataInputStream support for basic data types (binary) BufferedInputStream add buffering to existing stream LineNumberInputStream count lines of input PushBackInputStream allow bytes to be placed back into the stream for rereading plus: Additional classes providing support for data decompression and security The basic classes derived from FilterInputStream provide the ability to transform the simple input obtained from an InputStream source. You might call this "decorated" input. You can also think of these as wrappers that are placed around the simpler InputStream classes to enhance or modify their capabilities. January 19 Nova Southeastern University Copyright Dr. Tim Margush
12
Character Input Streams
1/1/2019 Character Input Streams Derived from Reader Provides automatic character code conversion from native encoding method StringReader CharArrayReader PipedReader InputStreamReader FileReader BufferedReader LineNumberReader FilterReader PushBackReader Character input provides the basic support for character data, automatically converting from the native character format to internal Unicode representation. In general, you should try a Reader class first; there are specialized applications that require an InputStream. These basic classes allow input from Strings or character arrays, and a pipe created in another thread. Reader provides basic support for reading characters. A ready() function can be used to determine if the stream is ready to be read. January 19 Nova Southeastern University Copyright Dr. Tim Margush
13
Text File Input: Step-by-Step
1/1/2019 Text File Input: Step-by-Step Construct a new FileReader object Requires a file name Use the FileReader object to construct a new BufferedReader object Use readLine method to extract each line of text This line might then be tokenized and the individual tokens parsed as necessary January 19 Nova Southeastern University Copyright Dr. Tim Margush
14
Text File Input: Step-by-Step
1/1/2019 Text File Input: Step-by-Step It is customary to name only the last object in the sequence BufferedReader theFile = new BufferedReader( new FileReader("sample.txt") ); String aLine = theFile.readLine(); int age = Integer.parseInt(aLine); theFile.close(); January 19 Nova Southeastern University Copyright Dr. Tim Margush
15
Reading from Standard Input
Change System.in from DataInputStream to InputStreamReader Wrap a BufferedReader around the resulting InputStreamReader Use any of the Reader methods to obtain input typically read and readLine January 19 Nova Southeastern University Copyright Dr. Tim Margush
16
Reading from Standard Input
BufferedReader stdin = new BufferedReader( new InputStreamReader( System.in ) ); String aLine = stdin.readLine(); January 19 Nova Southeastern University Copyright Dr. Tim Margush
17
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
1/1/2019 Formatted Input java.io.StreamTokenizer used to split character data into meaningful tokens that can be parsed by other methods method nextToken() parses the next token of the Stream and places its value in a public instance variable double nval or String sval TT_NUMBER, TT_WORD, TT_EOF, TT_EOL A StreamTokenizer class is built on an existing character stream. By calling nextToken(), enough characters are processed from the stream to determine a numeric or String value. nextToken() returns an int, one of TT_NUMBER, TT_WORD, TT_EOF, TT_EOL TT_EOL is set only if the tokenizer has been requested to detect end of line markers by calling its eolIsSignificant(true) method. January 19 Nova Southeastern University Copyright Dr. Tim Margush
18
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
1/1/2019 StringTokenizer java.util.StringTokenizer nextToken() method returns a substring with no whitespace BufferedReader contains readLine() method Conversion Integer.parseInt(x); //decimal Integer.parseInt(x,16); //hex input etc Another way to do formatted input is to use the StringTokenizer class. You will need to read information from the stream into a String, then use this object to will parse the stream into substrings. Each substring can be explicitly parsed using the parse or type conversion methods of the primitive type wrapper classes. By using the BufferedReader class, you can call the readLine() method to input a line of text from the stream. January 19 Nova Southeastern University Copyright Dr. Tim Margush
19
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
1/1/2019 OutputStream Methods write(int b); write(byte[] b); write(byte[] b, int offset, int length); flush(); close(); These methods define functionality - they are generally overridden in subclasses The first method writes one byte, the low order byte of the int. It is an abstract method, so must be implemented in a subclass. The rest are pretty much straightforward. flush and close do nothing - they will be implemented in a subclass as well. January 19 Nova Southeastern University Copyright Dr. Tim Margush
20
OutputStream Derivations
1/1/2019 OutputStream Derivations FileOutputStream stream is directed to a file ByteArrayOutputStream stream is directed to a byte array PipedOutputStream stream is intended to connect to a PipedInputStream FilterOutputStream a base class for further capabilities FileOutputStream is used to write data to a physical file. The constructor takes a File object. This class has a method, getFD() that returns a FileDescriptor object. This object can be used later to refer to the same file. The ByteArrayOutputStream is essentially a "file" stored in memory. An object of this type contains an array of bytes into which the output is written. The constructor allows you to specify the initial size of the array. The array will be automatically extended as needed. Various methods are included to access the contents of the byte array. PipedOutputStream objects connect to PipedInputStream objects. These generally run in different threads to enhance performance. The final class is a super class for nine additional output stream classes, including zip and gzip streams. January 19 Nova Southeastern University Copyright Dr. Tim Margush
21
Data and Buffered OutputStream Classes
1/1/2019 Data and Buffered OutputStream Classes Derived from FilterOutputStream DataOutputStream used to write primitive data in binary mode - no translation BufferedOutputStream adds buffering to improve performance Constructors require an object of one of the other OutputStream types These streams are designed to augment the functionality of one of the other stream types (File, ByteArray, or Piped). There are two other classes to be considered here - PrintStream and PrintWriter. These classes provide the ability to output most basic types as strings. PrintWriter is new to Java 1.1 and is intended to replace PrintStream. System.out is of type PrintStream. January 19 Nova Southeastern University Copyright Dr. Tim Margush
22
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
1/1/2019 DataOutputStream Used when writing data that is not strictly character data creates a sequence of bytes corresponding to the internal representation of data methods exist to write all of the primitive types as well as a String results are usually not human readable typically used to store data in a file to be reread later This class is used to create binary content files. Writing an int will send 4 bytes to the file. These are not digits, but the four bytes found in memory that represent the 2’s complement code for the int. Other data types are handled similarly. January 19 Nova Southeastern University Copyright Dr. Tim Margush
23
Character Output Streams
1/1/2019 Character Output Streams StringWriter CharArrayWriter PipedWriter OutputStreamWriter PrintWriter provides String output for other Writers BufferedWriter buffers other Writers FilterWriter None of these are directly related to a file FileWriter derived from OutputStreamWriter writes data to a File named in the constructor The first two classes write to a String or Character Array in memory. The OutputStreamWriter is used to convert from unicode to local machine representation of the characters. The constructor requires an OutputStream object that specifies the destination. Remember that OutputStream is a byte stream. The FileWriter class has a constructor that takes a File object. This is how you can write data to a file in character form. To convert from numeric data such as int and float, use the PrintWriter class. January 19 Nova Southeastern University Copyright Dr. Tim Margush
24
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
1/1/2019 PrintWriter Constructed from a Writer or an OutputStream object Used to output formatted representations of objects to a text stream Includes print() and println() methods these are overloaded for all of the basic types and will output any object using its toString method PrintWriter allows direct output of any object (using toString) and all of the primitive types. The character results are eventually translated to a byte stream at one of the lower levels using the host’s character encoding. The constructors accept a second argument (true) to indicate that automatic flushing is to occur when the println() method is called (the default is false). No exceptions are thrown by this class - you must call checkError() to determine if any errors have occurred. January 19 Nova Southeastern University Copyright Dr. Tim Margush
25
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
1/1/2019 Formatting Output java.text contains numerous classes dealing with text - data conversions Support is provided for internationalization via getLocale() After creating a format object, it may be used to format data (convert to String representations) Formatting output is complicated due to the many formats that might be desired by a programmer. The java.text package provides support for converting from internal representations of dates, times, and numbers to String formats used for display. The package also provides parse capability to convert String representations back to internal format. January 19 Nova Southeastern University Copyright Dr. Tim Margush
26
Text File Output: Step-by-Step
1/1/2019 Text File Output: Step-by-Step Construct a new FileWriter object Requires a file name Use the FileWriter object to construct a new BufferedWriter object Use the BufferedWriter object to construct a new PrintWriter object Use print and println methods January 19 Nova Southeastern University Copyright Dr. Tim Margush
27
Text File Output: Step-by-Step
1/1/2019 Text File Output: Step-by-Step It is customary to name only the last object in the sequence PrintWriter theFile = new PrintWriter( new BufferedWriter( new FileWriter("sample.txt") ) ); theFile.print("The answer is: "); theFile.println(2+2); January 19 Nova Southeastern University Copyright Dr. Tim Margush
28
Text File Output: Step-by-Step
1/1/2019 Text File Output: Step-by-Step All streams should be closed when they are no longer needed Closing the PrintWriter causes the BufferedWriter to close which in turn causes the FileWriter to close theFile.close(); January 19 Nova Southeastern University Copyright Dr. Tim Margush
29
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
Serializable A class that implements the Serializable interface knows how to convert itself to a sequence of bytes and how to restore itself from a sequence of bytes Used to store/restore objects in files Used to implement persistence Used to transmit objects across a network Required for RMI (Remote Method Invocation) January 19 Nova Southeastern University Copyright Dr. Tim Margush
30
Serializing and Deserializing
To serialize Create some type of OutputStream object Wrap it in an ObjectOutputStream object Call writeObject() To deserialize Create an InputStream object Wrap it in an ObjectInputStream object Call readObject() Returns a new, restored (deserialized) Object January 19 Nova Southeastern University Copyright Dr. Tim Margush
31
Object I/O - Serialization
1/1/2019 Object I/O - Serialization ObjectOutputStream created from a DataOutputStream contains writeObject() method Object must implement the Serializable Interface No methods need to be implemented to do this! ObjectInputStream created from a DataInputStream contains readObject() method Object being restored must be Serializable A Serializable object knows how to output all of its members. The file created from writeObject contains the information needed to recreate the object. The information is stored in binary format for efficiency. Restoring an object from the file is equally easy. January 19 Nova Southeastern University Copyright Dr. Tim Margush
32
implements Serializable
1/1/2019 implements Serializable This one is easy - there are no special methods that you are required to implement! All the data members must be a basic data type, or an object that is itself Serializable or marked as transient Members to be omitted from the object stream are declared transient The Serializable interface shows the programmer’s intent to serialize an object. If some data members are not to be written to the stream, they are declared as transient. Transient data members are (of course) not restored by the readObject method. The object constructed by readObject must be typecast to the appropriate type. January 19 Nova Southeastern University Copyright Dr. Tim Margush
33
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
Deeply Serializable When an object is serialized, all object references contained inside it (composition) are serialized along with it. An array of objects can be serialized and restored (the objects must implement Serializable) Static fields are not stored when an object is serialized January 19 Nova Southeastern University Copyright Dr. Tim Margush
34
Nova Southeastern University Copyright 2001 - Dr. Tim Margush
1/1/2019 Deep Copies By serializing an object, and deserializing, you can make a deep copy of an object SomeClass [] original; //an array of objects ByteArrayOutputStream buffer = new ByteArrayOutputStream() ObjectOutputStream outStream = new ObjectOutputStream(buffer); outStream.writeObject(original); //serialized ObjectInputStream inStream = new ObjectInputStream(buffer.toByteArray()); SomeClass [] copy = (SomeClass []) inStream.readObject(); SomeClass is a class that implements Seriazable Assume the array named orginal has been instantiated and filled with objects. Create a buffer in memory and use it to store the serialized array Deserialize the buffer to an object and cast it to the appropriate type Viola! a "deep copy" of the array has been created as the deserialized array and objects stored in the array will occupy new memory locations from the original ones. January 19 Nova Southeastern University Copyright Dr. Tim Margush
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.