Chapter 15: Input and Output F Stream Classes F Processing External Files F Data Streams F Print...

44
Chapter 15: Input and Output Stream Classes Stream Classes Processing External Files Processing External Files Data Streams Data Streams Print Streams Print Streams Buffered Streams Buffered Streams Use JFileChooser Use JFileChooser Text Input and Output on the Text Input and Output on the Console Console Random Access Files Random Access Files Parsing Text Files Parsing Text Files

Transcript of Chapter 15: Input and Output F Stream Classes F Processing External Files F Data Streams F Print...

Chapter 15: Input and Output Stream ClassesStream Classes Processing External FilesProcessing External Files Data StreamsData Streams Print StreamsPrint Streams Buffered StreamsBuffered Streams Use JFileChooser Use JFileChooser Text Input and Output on the ConsoleText Input and Output on the Console Random Access FilesRandom Access Files Parsing Text FilesParsing Text Files

Streams A A streamstream is an abstraction of the continuous one- is an abstraction of the continuous one-

way flow of data. way flow of data.

Program

Output Stream

File

Input Stream

Stream Classes The stream classes can be categorized into two The stream classes can be categorized into two

types: types: byte streamsbyte streams and and character streamscharacter streams..

The InputStream/OutputStream class is theThe InputStream/OutputStream class is theroot of all byte stream classes, and the root of all byte stream classes, and the Reader/Writer class is the root of all character Reader/Writer class is the root of all character stream classes. stream classes.

The subclasses of InputStream/OutputStream The subclasses of InputStream/OutputStream are analogous to the subclasses of are analogous to the subclasses of Reader/WriterReader/Writer..

Byte Stream Classes

InputStream

OutputStream

RandomAccessFile

Object

PipeOutputStream

SequenceInputStream

StringBufferInputStream

ByteArrayOutputStream

ObjectOutputStream

FilterOutputStream

FileOutputStream

PipedInputStream

PushBackInputStream

BufferedInputStream

LineNumberInputStream

DataInputStream

BufferedOutputStream

DataOutputStream

PrintStream

ObjectInputStream

FilterInputStream

FileInputStream

ByteArrayInputStreamInputData

OutputData

ObjectOutput

ObjectInput

Character Stream Classes

Reader

Writer

StreamTokenizer

Object

PrintWriter

BufferedWriter

CharArrayWriter

PipedWriter

FilterWriter

PipedReader

LineNumberReader

FileReader

PushBackReader

FileWriter

StringWriter

StringReader

InputStreamReader

CharArrayReader

BufferedReader

FilterReader

OutputStreamWriter

InputStream abstract int read() throws IOExceptionabstract int read() throws IOException

Return a byte [0..255] or –1 (EOF)Return a byte [0..255] or –1 (EOF)

int read(byte b[]) throws IOExceptionint read(byte b[]) throws IOException

Read bytes into array and return b.lengthRead bytes into array and return b.length

void close() throws IOExceptionvoid close() throws IOException

Int available() throws IOExceptionInt available() throws IOException

Return the number of bytes to be readReturn the number of bytes to be read

long skip(long n) throws IOExceptionlong skip(long n) throws IOException

Skip over n bytesSkip over n bytes

Reader

The The ReaderReader class is similar to the InputStream class is similar to the InputStream class. The methods in class. The methods in ReaderReader are subject to are subject to character interpretation.character interpretation.

abstract int read() throws IOException

int read(char b[]) throws IOException

void close() throws IOException

long skip(long n) throws IOException

Note that if no data are available, it blocks the thread from executing next statement.

OutputStream

abstract void write(int b) throws IOExceptionabstract void write(int b) throws IOException

void write(byte[] b) throws IOExceptionvoid write(byte[] b) throws IOException

void close() throws IOExceptionvoid close() throws IOException

void flush() throws IOExceptionvoid flush() throws IOException

Writer

abstract void write(int b) throws IOExceptionabstract void write(int b) throws IOException

void write(char[] b) throws IOExceptionvoid write(char[] b) throws IOException

void close() throws IOExceptionvoid close() throws IOException

void flush() throws IOExceptionvoid flush() throws IOException

Processing External Files You must use file streams to read from or write You must use file streams to read from or write to a disk file. to a disk file. You can use You can use FileInputStreamFileInputStream or or FileOutputStreamFileOutputStream for byte streams, and you can for byte streams, and you can use use FileReaderFileReader or or FileWriterFileWriter for character for character streams. streams.

File I/O Stream Constructors

Constructing instances of Constructing instances of FileInputStreamFileInputStream, , FileOutputStreamFileOutputStream, , FileReaderFileReader, and , and FileWriter FileWriter from file from file names:names:

FileInputStream infile = new FileInputStream("in.dat");

FileOutputStream outfile = new FileOutputStream("out.dat");

FileReader infile = new FileReader("in.dat");

FileWriter outfile = new FileWriter("out.dat");

Example 15.1Processing External Files

CopyFileUsingByteStreamCopyFileUsingByteStream

RunRun

Click the Run button to access the DOS prompt; then type java CopyFileUsingByteStream ButtonDemo.java t.java and press Enter. (If working from the CD, add a path to the hard disk or floppy disk drive for t.java.)

Data Streams

The data streams (The data streams (DataInputStreamDataInputStream and and DataOutputStreamDataOutputStream) read and write Java primitive ) read and write Java primitive types in a machine-independent fashion, which types in a machine-independent fashion, which enables you to write a data file in one machine enables you to write a data file in one machine and read it on another machine that has a and read it on another machine that has a different operating system or file structure. different operating system or file structure.

DataInputStream Methods int readByte() throws IOExceptionint readByte() throws IOException

int readShort() throws IOExceptionint readShort() throws IOException

int readInt() throws IOExceptionint readInt() throws IOException

int readLong() throws IOExceptionint readLong() throws IOException

float readFloat() throws IOExceptionfloat readFloat() throws IOException

double readDouble() throws IOExceptiondouble readDouble() throws IOException

char readChar() throws IOExceptionchar readChar() throws IOException

boolean readBoolean() throwsboolean readBoolean() throwsIOExceptionIOException

String readUTF() throws IOExceptionString readUTF() throws IOException

DataOutputStream Methods void writeByte(byte b) throws IOException void writeByte(byte b) throws IOException

void writeShort(short s) throws IOException void writeShort(short s) throws IOException

void writeInt(int i) throws IOException void writeInt(int i) throws IOException

void writeLong(long l) throws IOException void writeLong(long l) throws IOException

void writeFloat(float f) throws IOException void writeFloat(float f) throws IOException

void writeDouble(double d) throws IOException void writeDouble(double d) throws IOException

void writeChar(char c) throws IOException void writeChar(char c) throws IOException

void writeBoolean(boolean b) throws IOExceptionvoid writeBoolean(boolean b) throws IOException

void writeBytes(String l) throws IOExceptionvoid writeBytes(String l) throws IOException

void writeChars(String l) throws IOExceptionvoid writeChars(String l) throws IOException

void writeUTF(String l) throws IOException void writeUTF(String l) throws IOException

Data I/O Stream Constructors DataInputStream infile = newDataInputStream infile = new

DataInputStream(new FileInputStream("in.dat"));DataInputStream(new FileInputStream("in.dat"));Creates an input file for in.dat.Creates an input file for in.dat.

DataOutputStream outfile = newDataOutputStream outfile = newDataOutputStream(new FileOutputStream("out.dat"));DataOutputStream(new FileOutputStream("out.dat"));Creates an output file for out.dat.Creates an output file for out.dat.

Example 15.2Using Data Streams

TestDataStreamsTestDataStreams

RunRun

Click the Run button to access the DOS prompt; then type java TestDataStreams and press Enter. (Note: You cannot run this from the CD; the program writes to disk.)

Print Streams

The data output stream outputs a binary The data output stream outputs a binary representation of data, so you cannot view its representation of data, so you cannot view its contents as text. In Java, you can use print contents as text. In Java, you can use print streams to output data into files. These files can streams to output data into files. These files can be viewed as text.be viewed as text.

The The PrintStreamPrintStream and and PrintWriterPrintWriter classes provide classes provide this functionality.this functionality.

PrintWriter Constructors PrintWriter(Writer out)PrintWriter(Writer out)

PrintWriter(Writer out, boolean autoFlush)PrintWriter(Writer out, boolean autoFlush)

PrintWriter(OutputStream out)PrintWriter(OutputStream out)

PrintWriter(OutputStream out, boolean PrintWriter(OutputStream out, boolean autoFlush)autoFlush)

PrintWriter Methods void print(Object o)void print(Object o) void print(String s)void print(String s) void println(String s)void println(String s) void print(char c)void print(char c) void print(char[] cArray)void print(char[] cArray) void print(int i)void print(int i) void print(long l)void print(long l) void print(float f)void print(float f) void print(double d)void print(double d) void print(boolean b)void print(boolean b)

Example 15.3Using Print Streams

RunRun

TestPrintWritersTestPrintWriters

Click the Run button to access the DOS prompt; then type java TestPrintWriters t.dat and press Enter. (Note: You cannot run this from the CD; the program writes to disk.)

Buffered Streams

Java introduces buffered streams that speed Java introduces buffered streams that speed up input and output by reducing the number of up input and output by reducing the number of reads and writes. In the case of input, a reads and writes. In the case of input, a bunch of data is read all at once instead of bunch of data is read all at once instead of one byte at a time. In the case of output, data one byte at a time. In the case of output, data are first cached into a buffer, then written all are first cached into a buffer, then written all together to the file. together to the file.

Using buffered streams is highly Using buffered streams is highly recommended.recommended.

Buffered Stream Constructors BufferedInputStream (InputStream in) BufferedInputStream (InputStream in)

Default buffer size = 512 bytesDefault buffer size = 512 bytes

BufferedInputStream (InputStream in, int bufferSize) BufferedInputStream (InputStream in, int bufferSize)

BufferedOutputStream (OutputStream in) BufferedOutputStream (OutputStream in)

BufferedOutputStream (OutputStream in, int bufferSize)BufferedOutputStream (OutputStream in, int bufferSize)

BufferedReader(Reader in)BufferedReader(Reader in)

Default buffer size = 512 charsDefault buffer size = 512 chars

BufferedReader(Reader in, int bufferSize)BufferedReader(Reader in, int bufferSize)

BufferedWriter(Writer out)BufferedWriter(Writer out)

BufferedWriter(Writer out, int bufferSize)BufferedWriter(Writer out, int bufferSize)

Example 15.4Displaying a File in a Text Area

Objective: View a file in a text area. The user Objective: View a file in a text area. The user enters a filename in a text field and clicks the enters a filename in a text field and clicks the View button; the file is then displayed in a View button; the file is then displayed in a text area.text area.

ViewFileViewFile

RunRun

JFileChooser

public JFileChooser()public JFileChooser() public JFileChooser(String currentDirPath)public JFileChooser(String currentDirPath) public JFileChooser(File currentDirectory)public JFileChooser(File currentDirectory) File selectedFileFile selectedFile File[] selectedFilesFile[] selectedFiles boolean multiSelectionEnabledboolean multiSelectionEnabled File currentDirectoryFile currentDirectory public int showOpenDialog(Component pnt)public int showOpenDialog(Component pnt)

Example 15.5Using File Dialogs Objective: Create a simple notepad using Objective: Create a simple notepad using

JFileChooserJFileChooser to open and save files. The to open and save files. The notepad enables the user to open an existing notepad enables the user to open an existing file, edit the file, and save the note into the file, edit the file, and save the note into the current file or to a specified file. You can current file or to a specified file. You can display and edit the file in a text area.display and edit the file in a text area.

RunRunFileDialogDemoFileDialogDemo

Note: You cannot run this from the CD; the programwrites to disk.

Text Input and Output on the Consoles

There are two types of interactive I/O. There are two types of interactive I/O. Text interactive I/O: simple input from the Text interactive I/O: simple input from the keyboard and simple output in a pure text form. keyboard and simple output in a pure text form. Graphical interactive I/O: input from various Graphical interactive I/O: input from various input devices and output to a graphical input devices and output to a graphical environment on frames and applets. environment on frames and applets.

Console Output/Input

To perform console output, you can use any To perform console output, you can use any of the methods for PrintStream in System.out. of the methods for PrintStream in System.out. Keyboard input is not directly supported in Keyboard input is not directly supported in Java. See MyInput.JavaJava. See MyInput.Java

call readString() to get a stringcall readString() to get a string parse the string to byte, short, int, float, …parse the string to byte, short, int, float, …

MyInputMyInput

Object Streams

Object streams enable you to perform input Object streams enable you to perform input and output at the object level. and output at the object level.

To enable an object to be read or write, the To enable an object to be read or write, the object's defining class has to implement the object's defining class has to implement the java.io.Serializablejava.io.Serializable interface or the interface or the java.io.Externalizablejava.io.Externalizable interface. interface.

The Serializable Interface

The The SerializableSerializable interface is a marker interface is a marker interface. It has no methods, so you don't interface. It has no methods, so you don't need to add additional code in your class that need to add additional code in your class that implements implements SerializableSerializable..

Implementing this interface enables the Java Implementing this interface enables the Java serialization mechanism to automate the serialization mechanism to automate the process of storing the objects and arrays. process of storing the objects and arrays.

The Object Streams

Use the ObjectOutputStream class for Use the ObjectOutputStream class for storing/writing objects (object serialization) and storing/writing objects (object serialization) and Use the ObjectInputStream class for Use the ObjectInputStream class for restoring/reading objects (object deserialization) . restoring/reading objects (object deserialization) . These two classes are built upon several other These two classes are built upon several other classes. (see next page)classes. (see next page) Note that all JavaBeans components implement Note that all JavaBeans components implement Serializable.Serializable.

The ObjectOutput and ObjectInput Streams

Object

OutputStream

DataOutput ObjectOutput

ObjectOutputStream

ObjectStreamConstants

InputStream ObjectInputStream

DataIntput ObjectIntput

Example 15.6Testing Object Streams

Objective: Objective: Stores objects of MessagePanel and Stores objects of MessagePanel and Date, and Restores these objects.Date, and Restores these objects.

RunRunObjectStreamDemoObjectStreamDemo

Note: You cannot run this from the CD; the programwrites to disk.

Random Access Files Java provides the Java provides the RandomAccessFileRandomAccessFile class to class to

allow a file to be read and updated at the allow a file to be read and updated at the same time. same time.

The The RandomAccessFileRandomAccessFile class extends class extends ObjectObject and implements and implements DataInputDataInput and and DataOutputDataOutput interfaces.interfaces.

RandomAccessFile MethodsMany methods in Many methods in RandomAccessFileRandomAccessFile are the same as those are the same as those in in DataInputStreamDataInputStream and and DataOutputStreamDataOutputStream. For example, . For example, readInt()readInt(), , readLong()readLong(), , writeDouble()writeDouble(), , readLine()readLine(), , writeInt()writeInt(), and , and writeLong()writeLong() can be used in data input stream or data output can be used in data input stream or data output stream as well as in stream as well as in RandomAccessFileRandomAccessFile streams. streams.

RandomAccessFile Methods, cont.

void seek(long pos) throws IOException;void seek(long pos) throws IOException;

Sets the offset from the beginning of the Sets the offset from the beginning of the RandomAccessFileRandomAccessFile stream to where the next read stream to where the next reador write occurs.or write occurs.

long getFilePointer() IOException;long getFilePointer() IOException;

Returns the current offset, in bytes, from theReturns the current offset, in bytes, from thebeginning of the file to where the next readbeginning of the file to where the next reador write occurs.or write occurs.

RandomAccessFile Methods, cont.

long length()IOExceptionlong length()IOException

Returns the length of the file.Returns the length of the file.

final void writeChar(int v) throws IOExceptionfinal void writeChar(int v) throws IOException

Writes a character to the file as a two-byte Writes a character to the file as a two-byte Unicode, with the high byte written first.Unicode, with the high byte written first.

final void writeChars(String s)final void writeChars(String s)throws IOExceptionthrows IOException

Writes a string to the file as a sequence ofWrites a string to the file as a sequence ofcharacters.characters.

RandomAccessFile Constructor

RandomAccessFile raf =RandomAccessFile raf =new RandomAccessFile("test.dat", "rw"); //allows new RandomAccessFile("test.dat", "rw"); //allows read and writeread and write

RandomAccessFile raf =RandomAccessFile raf =new RandomAccessFile("test.dat", "r"); //read new RandomAccessFile("test.dat", "r"); //read onlyonly

Example 15. 7 Using Random Access Files

Objective: Create a program that registers Objective: Create a program that registers students and displays student information. students and displays student information.

RunRun

TestRandomAccessFileTestRandomAccessFile

Note: You cannot run this from the CD; the programwrites to disk.

Parsing Text Files (Optional) The The StreamTokenizerStreamTokenizer class lets you take an class lets you take an input stream and parse it into words, which input stream and parse it into words, which are known as are known as tokenstokens. . The tokens are read one at a time. The tokens are read one at a time. The following is the The following is the StreamTokenizerStreamTokenizer constructor:constructor:

StreamTokenizer st = StreamTokenizer(Reader is) StreamTokenizer st = StreamTokenizer(Reader is)

StreamTokenizer Constants TT_WORDTT_WORD

The token is a word.The token is a word.

TT_NUMBERTT_NUMBER

The token is a number.The token is a number.

TT_EOLTT_EOL

The end of the line has been read.The end of the line has been read.

TT_EOFTT_EOF

The end of the file has been read.The end of the file has been read.

StreamTokenizer Variables int ttypeint ttype

Contains the current token type, which matches Contains the current token type, which matches one of the constants listed on the preceding slide.one of the constants listed on the preceding slide.

double nvaldouble nvalContains the value of the current token if that Contains the value of the current token if that token is a number.token is a number.

String svalString svalContains a string that gives theContains a string that gives thecharacters of the current token if thatcharacters of the current token if thattoken is a word. token is a word.

StreamTokenizer Methods public int nextToken() throws IOExceptionpublic int nextToken() throws IOException

Parses the next token from the input stream of this Parses the next token from the input stream of this StreamTokenizer.StreamTokenizer.

The type of the next token is returned in the ttype field. The type of the next token is returned in the ttype field.

If ttype == TT_WORD, the token is storedIf ttype == TT_WORD, the token is storedin sval; in sval;

if ttype == TT_NUMBER, the token is stored in nval.if ttype == TT_NUMBER, the token is stored in nval.

Example 15.8Using StreamTokenizer

RunRunParsingTextFileParsingTextFile

Click the Run button to access the DOS prompt; then type java ParsingTextFile and press Enter. (Note: You cannot run this from the CD; the program writes to disk.)