Chapter 19 Chapter 19 Binary Input & Output Binary Input & Output Java I ITP 120 Java I ITP 120
May 11, 2015
Chapter 19 Chapter 19 Binary Input & Output Binary Input & Output
Java I ITP 120 Java I ITP 120
ITP 120 Java Programming I2
Patrick Healy
Class #15 – Input and Output Chapter Objectives
To understand how I/O is handled in Java To distinguish between text I/O and binary I/O To read and write bytes using FileInputStream and FileOutputStream To read and write primitive values and strings using the DataInputStream and
DataOutputStream classes To store and restore objects using ObjectOutputStream and ObjectInputStream, and
to understand how objects are serialized and what kind of objects can be serialized To use the Serializable interface to enable objects to be serializable (optional) To know how to serialize arrays (optional) To use RandomAccessFile for both read and write (Optional).
ITP 120 Java Programming I3
Patrick Healy
Class #15 – Input and Output Overview
The java.io.* package provides a library of classes to read and write various types of data.
In Java, all data I/O is handled in the form of streams Data streams can be byte streams or character streams The java.io package has classes that process byte streams of all types NOTE: In Java, a character is 2 BYTES ! Also NOTE: a Unicode character is 2 bytes ! The Reader and Writer classes process character streams. Streams can be layered, so that one type of streams can be converted
to another type of streams by chaining. Chaining a character stream reader to a byte stream reader to read bytes on one end and produce characters at the other end .
ITP 120 Java Programming I4
Patrick Healy
Class #15 – Input and Output
Overview --- Streams
A stream is an abstraction of a continuous one-way flow of data.
Program
Output Stream
File
Input Stream
ITP 120 Java Programming I5
Patrick Healy
Class #15 – Input and Output
2 Types of Stream Classes: Bytes & Characters
The stream classes can be categorized into two types: byte streams and character streams.
The InputStream/OutputStream class is theroot of all BYTE stream classes
The Reader/Writer class is the root of all CHARACTER streamclasses.
The subclasses of InputStream/OutputStream are analogous to the subclasses of Reader/Writer.
ITP 120 Java Programming I6
Patrick Healy
Class #15 – Input and Output
Byte Stream Classes (note: the word “stream” )
InputStream
OutputStream
RandomAccessFile
Object
PipeOutputStream
SequenceInputStream
StringBufferInputStream
ByteArrayOutputStream
ObjectOutputStream
FilterOutputStream
FileOutputStream
PipedInputStream
PushBackInputStream
BufferedInputStream
LineNumberInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
ByteArrayInputStream InputData
OutputData
ObjectOutput
ObjectInput
ITP 120 Java Programming I7
Patrick Healy
Class #15 – Input and Output Character Stream Classes (Character = 2 bytes)
Reader
Writer
StreamTokenizer
Object
PrintWriter
BufferedWriter
CharArrayWriter
PipedWriter
FilterWriter
PipedReader
LineNumberReader
FileReader
PushBackReader
FileWriter
StringWriter
StringReader
InputStreamReader
CharArrayReader
BufferedReader
FilterReader
OutputStreamWriter
How is I/O Handled in Java?A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes.
Formatter output = new Formatter("temp.txt");
output.format("%s", "Java 101");
output.close();
Scanner input = new Scanner(new File("temp.txt"));
System.out.println(input.nextLine());
Program
Input object created from an
input class
Output object created from an
output class
Input stream
Output stream
File
File 01011…1001
11001…1011
Text Files vs. Binary Files Data stored in a text file are represented in human-readable form. Data
stored in a binary file are represented in binary form. You cannot read binary files. Binary files are designed to be read by programs. For example, the Java source programs are stored in text files and can be read by a text editor, but the Java classes are stored in binary files and are read by the JVM. The advantage of binary files is that they are more efficient to process than text files.
Although it is not technically precise and correct, you can imagine that a text file consists of a sequence of characters and a binary file consists of a sequence of bits. For example, the decimal integer 199 is stored as the sequence of three characters: '1', '9', '9' in a text file and the same integer is stored as a byte-type value C7 in a binary file, because decimal 199 equals to hex C7.
Binary I/OText I/O requires encoding and decoding. The JVM converts a Unicode to a file specific encoding when writing a character and coverts a file specific encoding to a Unicode when reading a character. Binary I/O does not require conversions. When you write a byte to a file, the original byte is copied into the file. When you read a byte from a file, the exact byte in the file is returned.
Text I/O program
The Unicode of the character
Encoding/ Decoding
Binary I/O program
A byte is read/written (b)
(a)
e.g.,
"199"
The encoding of the character is stored in the file
0x31
e.g.,
199 00110111
00110001 00111001 00111001
0x39 0x39
0xC7
The same byte in the file
Binary I/O Classes
InputStream
OutputStream
Object
ObjectOutputStream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
java.io.InputStream
+read(): int
+read(b: byte[]): int
+read(b: byte[], off: int, len: int): int
+available(): int
+close(): void
+skip(n: long): long
+markSupported(): boolean
+mark(readlimit: int): void
+reset(): void
Reads the next byte of data from the input stream. The value byte is returned as an int value in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value –1 is returned.
Reads up to b.length bytes into array b from the input stream and returns the actual number of bytes read. Returns -1 at the end of the stream.
Reads bytes from the input stream and stores into b[off], b[off+1], …, b[off+len-1]. The actual number of bytes read is returned. Returns -1 at the end of the stream.
Returns the number of bytes that can be read from the input stream.
Closes this input stream and releases any system resources associated with the stream.
Skips over and discards n bytes of data from this input stream. The actual number of bytes skipped is returned.
Tests if this input stream supports the mark and reset methods.
Marks the current position in this input stream.
Repositions this stream to the position at the time the mark method was last called on this input stream.
The value returned is a byte as an int type.
InputStream
The value is a byte as an int type.
OutputStream
java.io.OutputStream
+write(int b): void
+write(b: byte[]): void
+write(b: byte[], off: int, len: int): void
+close(): void
+flush(): void
Writes the specified byte to this output stream. The parameter b is an int value. (byte)b is written to the output stream.
Writes all the bytes in array b to the output stream.
Writes b[off], b[off+1], …, b[off+len-1] into the output stream.
Closes this input stream and releases any system resources associated with the stream.
Flushes this output stream and forces any buffered output bytes to be written out.
FileInputStream/FileOutputStream
FileInputStream/FileOutputStream associates a binary input/output stream with an external file. All the methods in FileInputStream/FileOuptputStream are inherited from its superclasses.
InputStream
OutputStream
Object
ObjectOutputStream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
FileInputStreamTo construct a FileInputStream, use the following constructors:
public FileInputStream(String filename)
public FileInputStream(File file)
A java.io.FileNotFoundException would occur if you attempt to create a FileInputStream with a nonexistent file.
FileOutputStreamTo construct a FileOutputStream, use the following constructors:
public FileOutputStream(String filename)public FileOutputStream(File file)public FileOutputStream(String filename, boolean append)public FileOutputStream(File file, boolean append)
If the file does not exist, a new file would be created. If the file already exists, the first two constructors would delete the current contents in the file. To retain the current content and append new data into the file, use the last two constructors by passing true to the append parameter.
TestFileStreamTestFileStream RunRun
FilterInputStream/FilterOutputStream
Filter streams are streams that filter bytes for some purpose. The basic byte input stream provides a read method that can only be used for reading bytes. If you want to read integers, doubles, or strings, you need a filter class to wrap the byte input stream. Using a filter class enables you to read integers, doubles, and strings instead of bytes and characters. FilterInputStream and FilterOutputStream are the base classes for filtering data. When you need to process primitive numeric types, use DatInputStream and DataOutputStream to filter bytes.
InputStream
OutputStream
Object
ObjectOutputStream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
DataInputStream/DataOutputStreamDataInputStream reads bytes from the stream and converts them into appropriate primitive type values or strings.
InputStream
OutputStream
Object
ObjectOutputStream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
DataOutputStream converts primitive type values or strings into bytes and output the bytes to the stream.
DataInputStream
DataInputStream extends FilterInputStream and implements the DataInput interface.
java.io.DataInput
+readBoolean(): boolean
+readByte(): byte
+readChar(): char
+readFloat(): float
+readDouble(): float
+readInt(): int
+readLong(): long
+readShort(): short
+readLine(): String
+readUTF(): String
Reads a Boolean from the input stream.
Reads a byte from the input stream.
Reads a character from the input stream.
Reads a float from the input stream.
Reads a double from the input stream.
Reads an int from the input stream.
Reads a long from the input stream.
Reads a short from the input stream.
Reads a line of characters from input.
Reads a string in UTF format.
InputStream
FilterInputStream
DataInputStream
+DataInputStream( in: InputStream)
DataOutputStreamDataOutputStream extends FilterOutputStream and implements the DataOutput interface.
java.io.DataOutput
+writeBoolean(b: Boolean): void
+writeByte(v: int): void
+writeBytes(s: String): void
+writeChar(c: char): void
+writeChars(s: String): void
+writeFloat(v: float): void
+writeDouble(v: float): void
+writeInt(v: int): void
+writeLong(v: long): void
+writeShort(v: short): void
+writeUTF(s: String): void
Writes a Boolean to the output stream.
Writes to the output stream the eight low-order bits of the argument v.
Writes the lower byte of the characters in a string to the output stream.
Writes a character (composed of two bytes) to the output stream.
Writes every character in the string s, to the output stream, in order, two bytes per character.
Writes a float value to the output stream.
Writes a double value to the output stream.
Writes an int value to the output stream.
Writes a long value to the output stream.
Writes a short value to the output stream.
Writes two bytes of length information to the output stream, followed by the UTF representation of every character in the string s.
OutputStream
FilterOutputStream
DataOutputStream
+DataOutputStream( out: OutputStream)
Characters and Strings in Binary I/O A Unicode consists of two bytes. The writeChar(char c) method writes the Unicode of character c to the output. The writeChars(String s) method writes the Unicode for each character in the string s to the output.
Why UTF-8? What is UTF-8?
UTF-8 is a coding scheme that allows systems to operate with both ASCII and Unicode efficiently. Most operating systems use ASCII. Java uses Unicode. The ASCII character set is a subset of the Unicode character set. Since most applications need only the ASCII character set, it is a waste to represent an 8-bit ASCII character as a 16-bit Unicode character. The UTF-8 is an alternative scheme that stores a character using 1, 2, or 3 bytes. ASCII values (less than 0x7F) are coded in one byte. Unicode values less than 0x7FF are coded in two bytes. Other Unicode values are coded in three bytes.
Using DataInputStream/DataOutputStream
Data streams are used as wrappers on existing input and output streams to filter data in the original stream. They are created using the following constructors:
public DataInputStream(InputStream instream)public DataOutputStream(OutputStream outstream)
The statements given below create data streams. The first statement creates an input stream for file in.dat; the second statement creates an output stream for file out.dat.
DataInputStream infile = new DataInputStream(new FileInputStream("in.dat"));DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat"));
TestDataStreamTestDataStream RunRun
Checking End of File
TIP: If you keep reading data at the end of a stream, an EOFException would occur. So how do you check the end of a file? You can use input.available() to check it. input.available() == 0 indicates that it is the end of a file.
Order and Format
CAUTION: You have to read the data in the same order and same format in which they are stored. For example, since names are written in UTF-8 using writeUTF, you must read names using readUTF.
BufferedInputStream/BufferedOutputStream
Using buffers to speed up I/O
InputStream
OutputStream
Object
ObjectOutputStream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
BufferedInputStream/BufferedOutputStream does not contain new methods. All the methods BufferedInputStream/BufferedOutputStream are inherited from the InputStream/OutputStream classes.
Constructing BufferedInputStream/BufferedOutputStream
// Create a BufferedInputStream
public BufferedInputStream(InputStream in)
public BufferedInputStream(InputStream in, int bufferSize)
// Create a BufferedOutputStream
public BufferedOutputStream(OutputStream out)
public BufferedOutputStream(OutputStreamr out, int bufferSize)
Case Studies: Copy File This case study develops a program that copies files. The user needs to provide a source file and a target file as command-line arguments using the following command:
java Copy source target
The program copies a source file to a target file and displays the number of bytes in the file. If the source does not exist, tell the user the file is not found. If the target file already exists, tell the user the file already exists.
CopyCopy RunRun
Object I/O
DataInputStream/DataOutputStream enables you to perform I/O for primitive type values and strings. ObjectInputStream/ObjectOutputStream enables you to perform I/O for objects in addition for primitive type values and strings.
InputStream
OutputStream
Object
ObjectOutputStream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
Optional
ObjectInputStream
ObjectInputStream extends InputStream and implements ObjectInput and ObjectStreamConstants.
java.io.ObjectInput
+readObject(): Object
Reads an object.
java.io.InputStream
java.io.ObjectInputStream
+ObjectInputStream(in: InputStream)
java.io.DataInput
ObjectStreamConstants
ObjectOutputStream
ObjectOutputStream extends OutputStream and implements ObjectOutput and ObjectStreamConstants.
java.io.ObjectOutput
+writeObject(o: Object): void
Writes an object.
java.io.OutputStream
java.io.ObjectOutputStream
+ObjectOutputStream(out: OutputStream)
java.io.DataOutput
ObjectStreamConstants
Using Object StreamsYou may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/OutputStream using the following constructors:
// Create an ObjectInputStream
public ObjectInputStream(InputStream in)
// Create an ObjectOutputStream
public ObjectOutputStream(OutputStream out)
TestObjectOutputStreamTestObjectOutputStream RunRun
TestObjectInputStreamTestObjectInputStream RunRun
Random Access Files
All of the streams you have used so far are known as read-only or write-only streams. The external files of these streams are sequential files that cannot be updated without creating a new file. It is often necessary to modify files or to insert new records into files. Java provides the RandomAccessFile class to allow a file to be read from and write to at random locations.
RandomAccessFile
Creates a RandomAccessFile stream with the specified File object and mode.
Creates a RandomAccessFile stream with the specified file name string and mode.
Closes the stream and releases the resource associated with the stream.
Returns the offset, in bytes, from the beginning of the file to where the next read or write occurs.
Returns the length of this file.
Reads a byte of data from this file and returns –1 an the end of stream.
Reads up to b.length bytes of data from this file into an array of bytes.
Reads up to len bytes of data from this file into an array of bytes.
Sets the offset (in bytes specified in pos) from the beginning of the stream to where the next read or write occurs.
Sets a new length of this file.
Skips over n bytes of input discarding the skipped bytes.
Writes b.length bytes from the specified byte array to this file, starting at the current file pointer.
Writes len bytes from the specified byte array starting at offset off to this file.
DataInput
DataInput
java.io.RandomAccessFile
+RandomAccessFile(file: File, mode: String)
+RandomAccessFile(name: String, mode: String)
+close(): void
+getFilePointer(): long
+length(): long
+read(): int
+read(b: byte[]): int
+read(b: byte[], off: int, len: int) : int
+seek(long pos): void
+setLength(newLength: long): void
+skipBytes(int n): int
+write(b: byte[]): void
+write(byte b[], int off, int len) +write(b: byte[], off: int, len: int):
void
File PointerA random access file consists of a sequence of bytes. There is a special marker called file pointer that is positioned at one of these bytes. A read or write operation takes place at the location of the file pointer. When a file is opened, the file pointer sets at the beginning of the file. When you read or write data to the file, the file pointer moves forward to the next data. For example, if you read an int value using readInt(), the JVM reads four bytes from the file pointer and now the file pointer is four bytes ahead of the previous location.
byte
file
byte
…
byte
byte
byte
byte
byte
…
byte
byte
byte
byte
byte
file pointer
byte
file
byte
…
byte
byte
byte
byte
byte
…
byte
byte
byte
byte
byte
file pointer
(A) Before readInt()
(B) Before readInt()
RandomAccessFile MethodsMany methods in RandomAccessFile are the same as those in DataInputStream and DataOutputStream. For example, readInt(), readLong(), writeDouble(), readLine(), writeInt(), and writeLong() can be used in data input stream or data output stream as well as in RandomAccessFile streams.
RandomAccessFile Methods, cont.
void seek(long pos) throws IOException;Sets the offset from the beginning of the RandomAccessFile stream to where the next reador write occurs.
long getFilePointer() IOException;Returns the current offset, in bytes, from thebeginning of the file to where the next reador write occurs.
RandomAccessFile Methods, cont.
long length()IOExceptionReturns the length of the file.
final void writeChar(int v) throws IOExceptionWrites a character to the file as a two-byte Unicode, with the high byte written first.
final void writeChars(String s)throws IOExceptionWrites a string to the file as a sequence ofcharacters.
RandomAccessFile Constructor
RandomAccessFile raf =new RandomAccessFile("test.dat", "rw"); //allows read and write
RandomAccessFile raf =new RandomAccessFile("test.dat", "r"); //read only
Case Studies: Address BookOptional
Now let us use RandomAccessFile to create a useful project for storing and viewing and address book. The user interface of the program is shown in Figure 16.24. The Add button stores a new address to the end of the file. The First, Next, Previous, and Last buttons retrieve the first, next, previous, and last addresses from the file, respectively.
Fixed Length String I/O
Random access files are often used to process files of records. For convenience, fixed-length records are used in random access files so that a record can be located easily. A record consists of a fixed number of fields. A field can be a string or a primitive data type. A string in a fixed-length record has a maximum size. If a string is smaller than the maximum size, the rest of the string is padded with blanks.
Record 1
Record 2
Record n
Field1 Field 2 … Field k
file e.g.,
Student 1
Student 2
Student n
name street city state zip
FixedLengthStringIOFixedLengthStringIO
End of PresentationEnd of Presentation
Binary Input & Output Binary Input & Output Chapter 18 Chapter 18
ITP 120 Java Programming I41
Patrick Healy
Class #15 – Input and Output How is I/O Handled in Java?
A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes.
Formatter output = new Formatter(“outfile.txt");
output.format("%s", "Java 120"); // Write a string to outfile.txt
output.close(); // Close the output file outfile.txt
Scanner input = new Scanner(new File("temp.txt")); // Create object
System.out.println(input.nextLine()); // Read a line
Program
Input object created from an
input class
Output object created from an
output class
Input stream
Output stream
File
File 01011…1001
11001…1011
ITP 120 Java Programming I42
Patrick Healy
Class #15 – Input and Output Text Files vs. Binary Files
Data stored in a text file are represented in human-readable form. Data stored in a binary file are represented in binary form. You cannot read binary files. Binary files are designed to be read by programs. For example, the Java source programs are stored in text files and can be read by a text editor, but the Java classes are stored in binary files and are read by the JVM. The advantage of binary files is that they are more efficient to process than text files.
Although it is not technically precise and correct, you can imagine that a text file consists of a sequence of characters and a binary file consists of a sequence of bits. For example, the decimal integer 199 is stored as the sequence of three characters: '1', '9', '9' in a text file and the same integer is stored as a byte-type value C7 in a binary file ( Note: decimal 199 equals to Hex C7.)
ITP 120 Java Programming I43
Patrick Healy
Class #15 – Input and Output Binary File I/O
Text I/O requires encoding and decoding. The JVM converts a Unicode char to a file-specific encoding when writing a character and coverts a file-specific encoding to a Unicode char when reading a character. Binary I/O does not require conversions. When you write a byte to a file, the original byte is copied into the file. When you read a byte from a file, the exact byte in the file is returned.
Text I/O program
The Unicode of the character
Encoding/ Decoding
Binary I/O program
A byte is read/written (b)
(a)
e.g.,
"199"
The encoding of the character is stored in the file
0x31
e.g.,
199 00110111
00110001 00111001 00111001
0x39 0x39
0xC7
The same byte in the file
ITP 120 Java Programming I44
Patrick Healy
Class #15 – Input and Output Binary I/O Classes Inheritance Hierarchy
InputStream
OutputStream
Object
ObjectOutputStream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
ITP 120 Java Programming I45
Patrick Healy
Class #15 – Input and Output
java.io.InputStream
+read(): int
+read(b: byte[]): int
+read(b: byte[], off: int, len: int): int
+available(): int
+close(): void
+skip(n: long): long
+markSupported(): boolean
+mark(readlimit: int): void
+reset(): void
Reads the next byte of data from the input stream. The value byte is returned as an int value in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value –1 is returned.
Reads up to b.length bytes into array b from the input stream and returns the actual number of bytes read. Returns -1 at the end of the stream.
Reads bytes from the input stream and stores into b[off], b[off+1], …, b[off+len-1]. The actual number of bytes read is returned. Returns -1 at the end of the stream.
Returns the number of bytes that can be read from the input stream.
Closes this input stream and releases any system resources associated with the stream.
Skips over and discards n bytes of data from this input stream. The actual number of bytes skipped is returned.
Tests if this input stream supports the mark and reset methods.
Marks the current position in this input stream.
Repositions this stream to the position at the time the mark method was last called on this input stream.
The value returned is a byte as an int type.
InputStream (a byte stream class)
ITP 120 Java Programming I46
Patrick Healy
Class #15 – Input and Output
The value is a byte as an int type.
OutputStream ( a byte stream class)
java.io.OutputStream
+write(int b): void
+write(b: byte[]): void
+write(b: byte[], off: int, len: int): void
+close(): void
+flush(): void
Writes the specified byte to this output stream. The parameter b is an int value. (byte)b is written to the output stream.
Writes all the bytes in array b to the output stream.
Writes b[off], b[off+1], …, b[off+len-1] into the output stream.
Closes this input stream and releases any system resources associated with the stream.
Flushes this output stream and forces any buffered output bytes to be written out.
ITP 120 Java Programming I47
Patrick Healy
Class #15 – Input and Output
FileInputStream & FileOutputStream (byte streams)
FileInputStream/FileOutputStream associates a binary input/output stream with an external file. All the methods in FileInputStream/FileOuptputStream are inherited from its superclasses.
InputStream
OutputStream
Object
ObjectOutputStream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
ITP 120 Java Programming I48
Patrick Healy
Class #15 – Input and Output
FileInputStream (byte stream)
To construct a FileInputStream, use the following constructors:
public FileInputStream(String filename)
public FileInputStream(File file)
A java.io.FileNotFoundException would occur if you attempt to create a FileInputStream with a nonexistent file.
ITP 120 Java Programming I49
Patrick Healy
Class #15 – Input and Output FileOutputStream (byte stream)
To construct a FileOutputStream, use the following constructors:public FileOutputStream(String filename)public FileOutputStream(File file)public FileOutputStream(String filename, boolean append)public FileOutputStream(File file, boolean append) // append = true to add on to the file
If the file does not exist, a new file would be created. If the file already exists, the first two constructors would delete the current contents in the file. To retain the current content and append new data into the file, use the last two constructors by passing true to the append parameter.Demo Program: TestFileStream.java
ITP 120 Java Programming I50
Patrick Healy
Class #15 – Input and Output
FilterInputStream/FilterOutputStream
Filter streams are streams that filter bytes for some purpose. The basic byte input stream provides a read method that can only be used for reading bytes. If you want to read integers, doubles, or strings, you need a filter class to wrap the byte input stream. Using a filter class enables you to read integers, doubles, and strings instead of bytes and characters. FilterInputStream and FilterOutputStream are the base classes for filtering data. When you need to process primitive numeric types, use DataInputStream and DataOutputStream to filter bytes.
InputStream
OutputStream
Object
ObjectOutputStream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
ITP 120 Java Programming I51
Patrick Healy
Class #15 – Input and Output
DataInputStream & DataOutputStream (byte streams)DataInputStream reads bytes from the stream and converts them into appropriate primitive type values or strings.
InputStream
OutputStream
Object
ObjectOutputStream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
DataOutputStream converts primitive type values or strings into bytes and outputs the bytes to the stream.
ITP 120 Java Programming I52
Patrick Healy
Class #15 – Input and Output
DataInputStream ( byte stream)
DataInputStream extends FilterInputStream and implements the DataInput interface.
java.io.DataInput
+readBoolean(): boolean
+readByte(): byte
+readChar(): char
+readFloat(): float
+readDouble(): float
+readInt(): int
+readLong(): long
+readShort(): short
+readLine(): String
+readUTF(): String
Reads a Boolean from the input stream.
Reads a byte from the input stream.
Reads a character from the input stream.
Reads a float from the input stream.
Reads a double from the input stream.
Reads an int from the input stream.
Reads a long from the input stream.
Reads a short from the input stream.
Reads a line of characters from input.
Reads a string in UTF format.
InputStream
FilterInputStream
DataInputStream
+DataInputStream( in: InputStream)
ITP 120 Java Programming I53
Patrick Healy
Class #15 – Input and Output
DataOutputStream (byte stream)DataOutputStream extends FilterOutputStream and implements the DataOutput interface.
java.io.DataOutput
+writeBoolean(b: Boolean): void
+writeByte(v: int): void
+writeBytes(s: String): void
+writeChar(c: char): void
+writeChars(s: String): void
+writeFloat(v: float): void
+writeDouble(v: float): void
+writeInt(v: int): void
+writeLong(v: long): void
+writeShort(v: short): void
+writeUTF(s: String): void
Writes a Boolean to the output stream.
Writes to the output stream the eight low-order bits of the argument v.
Writes the lower byte of the characters in a string to the output stream.
Writes a character (composed of two bytes) to the output stream.
Writes every character in the string s, to the output stream, in order, two bytes per character.
Writes a float value to the output stream.
Writes a double value to the output stream.
Writes an int value to the output stream.
Writes a long value to the output stream.
Writes a short value to the output stream.
Writes two bytes of length information to the output stream, followed by the UTF representation of every character in the string s.
OutputStream
FilterOutputStream
DataOutputStream
+DataOutputStream( out: OutputStream)
ITP 120 Java Programming I54
Patrick Healy
Class #15 – Input and Output Characters and Strings in Binary I/O
A Unicode char is 2 bytes. The writeChar(char ch) method writes the Unicode of character ch to the output. The writeChars(String str) method writes the Unicode for each character in the string str to the output file.
What is UTF-8 ? Why use UTF-8 ? [ UTF means Unicode Text File ]
UTF-8 is a coding scheme that allows systems to operate with both ASCII and Unicode efficiently. Most operating systems use ASCII. Java uses Unicode. The ASCII character set is a subset of the Unicode character set. Since most applications need only the ASCII character set, it is a waste to represent an 8-bit ASCII character as a 16-bit Unicode character. The UTF-8 is an alternative scheme that stores a character using 1, 2, or 3 bytes. ASCII values (less than 0x7F) (127 decimal) are coded in one byte. Unicode values less than 0x7FF are coded in two bytes. Other Unicode values are coded in three bytes.
ITP 120 Java Programming I55
Patrick Healy
Class #15 – Input and Output
Using DataInputStream/DataOutputStream
Data streams are used as wrappers on existing input and output streams to filter data in the original stream. They are created using the following constructors:
public DataInputStream(InputStream instream)
public DataOutputStream(OutputStream outstream)
The statements below create data streams. The first statement creates an input stream for file in.dat; the second statement creates an output stream for file out.dat.
DataInputStream infile = new DataInputStream(new FileInputStream("in.dat"));DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat"));Demo Program: TestDataStream.java
ITP 120 Java Programming I56
Patrick Healy
Class #15 – Input and Output
Checking for the End of File (EOF)
TIP: If the program tried to read data at the end of a stream, an EOFException would occur. How do you check the end of a file? Use input.available() to check for EOF. if input.available() == 0 then the program is at the end of a file. (EOF)
Order and Format
CAUTION: You have to read the data in the same order and same format in which they are stored. For example, if names are written in UTF-8 using writeUTF (String str), you MUST read the names using the readUTF method.
ITP 120 Java Programming I57
Patrick Healy
Class #15 – Input and Output
BufferedInputStream/BufferedOutputStream Use buffers to speed up I/O processes
InputStream
OutputStream
Object
ObjectOutputStream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
BufferedInputStream/BufferedOutputStream does not contain new methods. All the methods BufferedInputStream/BufferedOutputStream are inherited from the InputStream/OutputStream classes.
ITP 120 Java Programming I58
Patrick Healy
Class #15 – Input and Output
Constructing BufferedInputStream/BufferedOutputStream
// Create a BufferedInputStreampublic BufferedInputStream(InputStream in)public BufferedInputStream(InputStream in, int bufferSize) // Create a BufferedOutputStream
public BufferedOutputStream(OutputStream out)
public BufferedOutputStream(OutputStream out, int bufferSize)
ITP 120 Java Programming I59
Patrick Healy
Class #15 – Input and Output
CopyFile.java
CopyFile.java is a program that copies files. The user needs to provide a source file and a target file as command-line arguments using the following command:
java CopyFile source target
Also: java CompFile source target
The program copies a source file to a target file and displays the number of bytes in the file. If the source does not exist, tell the user the file is not found. If the target file already exists, tell the user the file already exists.
ITP 120 Java Programming I60
Patrick Healy
Class #15 – Input and Output
Object I/O (optional)
DataInputStream/DataOutputStream enables you to perform I/O for primitive type values and strings. ObjectInputStream/ObjectOutputStream enables you to perform I/O for objects in addition for primitive type values and strings.
InputStream
OutputStream
Object
ObjectOutputStream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
ITP 120 Java Programming I61
Patrick Healy
Class #15 – Input and Output
ObjectInputStream (optional)
ObjectInputStream extends InputStream and implements ObjectInput and ObjectStreamConstants.
java.io.ObjectInput
+readObject(): Object
Reads an object.
java.io.InputStream
java.io.ObjectInputStream
+ObjectInputStream(in: InputStream)
java.io.DataInput
ObjectStreamConstants
ITP 120 Java Programming I62
Patrick Healy
Class #15 – Input and Output
ObjectOutputStream (optional)
ObjectOutputStream extends OutputStream and implements ObjectOutput and ObjectStreamConstants.
java.io.ObjectOutput
+writeObject(o: Object): void
Writes an object.
java.io.OutputStream
java.io.ObjectOutputStream
+ObjectOutputStream(out: OutputStream)
java.io.DataOutput
ObjectStreamConstants
ITP 120 Java Programming I63
Patrick Healy
Class #15 – Input and Output
Using Object Streams (optional)
You may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/OutputStream using the following constructors:
// Create an ObjectInputStreampublic ObjectInputStream(InputStream in) // Create an ObjectOutputStreampublic ObjectOutputStream(OutputStream out)
Demo: TestObjectOutputStream.java
TestObjectInputStream.java
ITP 120 Java Programming I64
Patrick Healy
Class #15 – Input and Output
The Serializable Interface
Not all objects can be written to an output stream. Objects that CAN be written to an object stream is said to be serializable. A serializable object is an instance of the java.io.Serializable interface. So the class of a serializable object must implement the Serializable interface.
The Serializable interface is a marker interface. It has no methods, so you don't need to add additional code in your class that implements Serializable.
Implementing this interface enables the Java serialization mechanism to automate the process of storing the objects and arrays.
ITP 120 Java Programming I65
Patrick Healy
Class #15 – Input and Output
The transient Keyword
If an object is an instance of Serializable, but it contains non-serializable instance data fields, can the object be serialized? The answer is NO !
To enable the object to be serialized, you can use the transient keyword to mark these data fields to tell the JVM to ignore these fields when writing the object to an object stream.
ITP 120 Java Programming I66
Patrick Healy
Class #15 – Input and Output The transient Keyword, cont.
Consider the following class:
public class ITP120 implements java.io.Serializable {
private int v1;
private static double v2;
private transient A v3 = new A();
}
class A { } // A is not serializable
When an object of the ITP120 class is serialized, only variable v1 is serialized. Variable v2 is not serialized because it is a static variable, and variable v3 is not serialized because it is marked transient. If v3 were not marked transient, a java.io.NotSerializableException would occur.
ITP 120 Java Programming I67
Patrick Healy
Class #15 – Input and Output
Serializing Arrays (optional)
An array is serializable if all its elements are serializable. So an entire array can be saved using writeObject into a file and later restored using readObject.
Listing 18.6 stores an array of five int values, an array of three strings, and an array of two JButton objects, and reads them back to display on the console.
Demo Program: TestObjectStreamForArray.java
ITP 120 Java Programming I68
Patrick Healy
Class #15 – Input and Output
Random Access Files
All of the streams you have used so far are known as read-only or write-only streams. The external files of these streams are sequential files that cannot be updated without creating a new file.
It is often necessary to modify files or to insert new records into files. Java provides the RandomAccessFile class to allow a file to be read from and write to at random locations.
ITP 120 Java Programming I69
Patrick Healy
Class #15 – Input and Output RandomAccessFile
Creates a RandomAccessFile stream with the specified File object and mode.
Creates a RandomAccessFile stream with the specified file name string and mode.
Closes the stream and releases the resource associated with the stream.
Returns the offset, in bytes, from the beginning of the file to where the next read or write occurs.
Returns the length of this file.
Reads a byte of data from this file and returns –1 an the end of stream.
Reads up to b.length bytes of data from this file into an array of bytes.
Reads up to len bytes of data from this file into an array of bytes.
Sets the offset (in bytes specified in pos) from the beginning of the stream to where the next read or write occurs.
Sets a new length of this file.
Skips over n bytes of input discarding the skipped bytes.
Writes b.length bytes from the specified byte array to this file, starting at the current file pointer.
Writes len bytes from the specified byte array starting at offset off to this file.
DataInput
DataInput
java.io.RandomAccessFile
+RandomAccessFile(file: File, mode: String)
+RandomAccessFile(name: String, mode: String)
+close(): void
+getFilePointer(): long
+length(): long
+read(): int
+read(b: byte[]): int
+read(b: byte[], off: int, len: int) : int
+seek(long pos): void
+setLength(newLength: long): void
+skipBytes(int n): int
+write(b: byte[]): void
+write(byte b[], int off, int len) +write(b: byte[], off: int, len: int):
void
ITP 120 Java Programming I70
Patrick Healy
Class #15 – Input and Output File Pointers
A random access file consists of a sequence of bytes. There is a special marker called file pointer that is positioned at one of these bytes. A read or write operation takes place at the location of the file pointer. When a file is opened, the file pointer sets at the beginning of the file. When you read or write data to the file, the file pointer moves forward to the next data. For example, if you read an int value using readInt(), the JVM reads four bytes from the file pointer and now the file pointer is four bytes ahead of the previous location.
ITP 120 Java Programming I71
Patrick Healy
Class #15 – Input and Output File Pointers
(moving the pointer 4 bytes ahead)
byte
file
byte
…
byte
byte
byte
byte
byte
…
byte
byte
byte
byte
byte
file pointer
byte
file
byte
…
byte
byte
byte
byte
byte
…
byte
byte
byte
byte
byte
file pointer
(A) Before readInt()
(B) Before readInt()
ITP 120 Java Programming I72
Patrick Healy
Class #15 – Input and Output
RandomAccessFile Methods
Many methods in RandomAccessFile are the same as those in
DataInputStream and DataOutputStream.
For example, readInt(), readLong(), writeDouble(), readLine(), writeInt(), and writeLong()
can be used in data input stream or data output stream as well as in RandomAccessFile streams.
ITP 120 Java Programming I73
Patrick Healy
Class #15 – Input and Output RandomAccessFile Methods, cont.
void seek(long pos) throws IOException;
Sets the offset from the beginning of the RandomAccessFile stream to where the next reador write occurs.
long getFilePointer() IOException;
Returns the current offset, in bytes, from thebeginning of the file to where the next reador write occurs.
ITP 120 Java Programming I74
Patrick Healy
Class #15 – Input and Output
RandomAccessFile Methods, cont.
long length()IOExceptionReturns the length of the file.
final void writeChar(int v) throws IOExceptionWrites a character to the file as a two-byte Unicode, with the high byte written first.
final void writeChars(String s)throws IOExceptionWrites a string to the file as a sequence ofcharacters.
ITP 120 Java Programming I75
Patrick Healy
Class #15 – Input and Output
RandomAccessFile Constructors
RandomAccessFile raf =new RandomAccessFile("test.dat", "rw"); //allows read and write to the file
RandomAccessFile raf =new RandomAccessFile("test.dat", "r"); //read only
Demo program: TestRandomAccessFile.java
(uses FixedLengthStringIO.java)
Case Study: Address BookNow let us use RandomAccessFile to create a useful project for storing and viewing and address book. The user interface of the program is shown in Figure 16.24. The Add button stores a new address to the end of the file. The First, Next, Previous, and Last buttons retrieve the first, next, previous, and last addresses from the file, respectively.
Run: AddressBook.java which uses FixedLengthStringIO.java
Fixed Length String I/O
Random access files are often used to process files of records. For convenience, fixed-length records are used in random access files so that a record can be located easily. A record consists of a fixed number of fields. A field can be a string or a primitive data type. A string in a fixed-length record has a maximum size. If a string is smaller than the maximum size, the rest of the string is padded with blanks.
Record 1
Record 2
Record n
Field1 Field 2 … Field k
file e.g.,
Student 1
Student 2
Student n
name street city state zip
FixedLengthStringIOFixedLengthStringIO
78
Chapter 18 Demo Programs
ReadBytes.java (skip) WriteData.java
WriteDemo.java ReadData.java
ShowFile.java
CopyFile.java CopyFileUsingByteStream.java
CompFile.java
RWData.java
RandomAccessDemo.java
PrintWriterDemo.java
ReadChars.java or BuffReader.java
ReadLines.java (BufferedReader)
79
Chapter 18 Demo Programs
TextFileScannerDemo.java Uses input file morestuff.txt
HasNextLineDemo.java Uses input file original.txt and creates output file numbered.txt
BufferReaderDemo.java Uses input file: buffer.txt
80
Chapter 18 Demo Programs
TestDataStreams.java
TestFileClass.java
TestPrintWriters.java
ViewFile.java (GUI text file viewer program)
needs MyFrameWithExitHanding.java class file
ParsingTextFile.java (needs grades.dat file)
(creates gradesout.dat)
TestRandomAccessFile.java AddressBook.java (creates file address.dat)
needs FixedLengthStringIO.class file
81
Chapter 18 Demo Programs
TestDataStream.java
TestFileReader.java (needs temp.txt)
TestFileStream.java
TestFileWriter.java (needs testdata.txt)
TestObjectStreamForArray.java ( creates array.dat)
TestObjectOutputStream.java
(creates object.dat)
TestObjectInputStream.java (reads object.dat)
ITP 120 Java Programming I82
Patrick Healy
Class #15 – Input and Output Chapter 18 Input / Output
Optional: More on Java File I/O Optional: More on Java File I/O Chapter 18 Java I ITP 120 Chapter 18 Java I ITP 120
ITP 120 Java Programming I83
Patrick Healy
Class #15 – Input and Output Chapter 18: More on Input and Output
Stream Classes (byte & character streams)Predefined Streams (System.in, System.out, System.err)Processing External FilesData StreamsPrint StreamsBuffered StreamsText Input and Output on the ConsoleRandom Access Files
ITP 120 Java Programming I84
Patrick Healy
Class #15 – Input and Output Chapter 18 Input /Output Objectives Understand input & output streams and learn how to create them. Discover the uses of byte and character streams. To know how to read from / write to external files using file streams. To become familiar with the File class. To use print streams to output data of primitive types in text format. To know how to read and write text data files. Use text input and output on the console. Use RandomAccessFile for reading & writing random access files.
ITP 120 Java Programming I85
Patrick Healy
Class #15 – Input and Output Overview The java.io.* package provides a library of classes to read and write
various types of data. In Java, all data I/O is handled in the form of streams Data streams can be byte streams or character streams The java.io package has classes that process byte streams of all types NOTE: In Java, a character is 2 BYTES ! NOTE: Unicode character is 2 bytes ! The Reader and Writer classes process character streams. Streams can be layered, so that one type of streams can be converted
to another type of streams by chaining. Chaining a character stream reader to a byte stream reader to read bytes on one end and produce characters at the other end .
ITP 120 Java Programming I86
Patrick Healy
Class #15 – Input and Output Overview Streams In Java, all Input/Output is handled by streams A stream is an abstraction of the continuous one-way flow of data Java streams can be applied to any source of data, so it is easy to get
input from the keyboard and send output to a monitor, and the same applies to file input & output.
All streams EXCEPT random-access file streams flow only in one direction.
See the diagram on the next slide
ITP 120 Java Programming I87
Patrick Healy
Class #15 – Input and Output
Overview --- Streams
A stream is an abstraction of a continuous one-way flow of data.
Program
Output Stream
File
Input Stream
ITP 120 Java Programming I88
Patrick Healy
Class #15 – Input and Output Overview and Background The original version of Java defined only the byte stream, but character
streams were quickly added. Byte streams can be used when reading or writing binary data. Character streams are designed for handling character I/O. Character streams use UNICODE. In Java, a character is 2 bytes Unicode is for the internationalization of Java in different languages. The Java I/O system is quite LARGE because of the TWO separate
class hierarchies of bytes and streams.
How is I/O Handled in Java?A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes.
Formatter output = new Formatter("temp.txt");
output.format("%s", "Java ITP 120");
output.close();
Scanner input = new Scanner(new File("temp.txt"));
System.out.println(input.nextLine());
Program
Input object created from an
input class
Output object created from an
output class
Input stream
Output stream
File
File 01011…1001
11001…1011
ITP 120 Java Programming I90
Patrick Healy
Class #15 – Input and Output Text Files vs. Binary Files
Data stored in a text file are represented in human-readable form. Data stored in a binary file are represented in binary form. You cannot read binary files. Binary files are designed to be read by programs. For example, the Java source programs are stored in text files and can be read by a text editor, but the Java classes are stored in binary files and are read by the JVM.
The advantage of binary files is that they are more efficient to process than text files.
Although it is not technically precise and correct, you can imagine that a text file consists of a sequence of characters and a binary file consists of a sequence of bits. For example, the decimal integer 199 is stored as the sequence of three characters: '1', '9', '9' in a text file and the same integer is stored as a byte-type value C7 in a binary file, because decimal 199 equals to hex C7 ( 12 x 16 + 7 = 192 + 7 = 199 decimal )
Binary I/OText I/O requires encoding and decoding. The JVM converts a Unicode character to file-specific encoding when writing a character, and coverts a file-specific encoding to a Unicode character when reading a character. Binary I/O does not require conversions. When you write a byte to a file, the original byte is copied into the file. When you read a byte from a file, the exact byte in the file is returned.
Text I/O program
The Unicode of the character
Encoding/ Decoding
Binary I/O program
A byte is read/written (b)
(a)
e.g.,
"199"
The encoding of the character is stored in the file
0x31
e.g.,
199 00110111
00110001 00111001 00111001
0x39 0x39
0xC7
The same byte in the file
ITP 120 Java Programming I92
Patrick Healy
Class #15 – Input and Output
2 Types of Stream Classes: Bytes & Characters
The stream classes can be categorized into two types: byte streams and character streams.
The InputStream/OutputStream class is theroot of all byte stream classes
The Reader/Writer class is the root of all character streamclasses.
The subclasses of InputStream/OutputStream are analogous to the subclasses of Reader/Writer.
ITP 120 Java Programming I93
Patrick Healy
Class #15 – Input and Output
Byte Stream Classes (note: “stream” )
InputStream
OutputStream
RandomAccessFile
Object
PipeOutputStream
SequenceInputStream
StringBufferInputStream
ByteArrayOutputStream
ObjectOutputStream
FilterOutputStream
FileOutputStream
PipedInputStream
PushBackInputStream
BufferedInputStream
LineNumberInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
ByteArrayInputStream InputData
OutputData
ObjectOutput
ObjectInput
ITP 120 Java Programming I94
Patrick Healy
Class #15 – Input and Output Character Stream Classes (Character = 2 bytes)
Reader
Writer
StreamTokenizer
Object
PrintWriter
BufferedWriter
CharArrayWriter
PipedWriter
FilterWriter
PipedReader
LineNumberReader
FileReader
PushBackReader
FileWriter
StringWriter
StringReader
InputStreamReader
CharArrayReader
BufferedReader
FilterReader
OutputStreamWriter
ITP 120 Java Programming I95
Patrick Healy
Class #15 – Input and Output Predefined Streams in Java All Java programs automatically import the java.lang package.
The java.lang package defines a class called System which encapsulates several aspects of the runtime environment.
The System class contains 3 predefined stream variables called:
in, out, and err (System.in, System.out, System.err)
These variables are declared as public and static with the System class. This means they can be used by any other part of your program and without a reference to a specific object in the System class.
ITP 120 Java Programming I96
Patrick Healy
Class #15 – Input and Output Predefined Streams in Java: System class
System.in refers to the standard input stream which is the keyboard by default. (Keyboard )
System.out refers to the standard output stream which is the console by default. (Monitor)
System.err refers to the standard error stream which is also the console by default. (Monitor)
These streams may be redirected to any compatible I/O device.
ITP 120 Java Programming I97
Patrick Healy
Class #15 – Input and Output Predefined Streams in Java: System class System.in is an object of type InputStream. (byte stream)
System.out is an object of type PrintStream. (byte stream)
System.err is an object of type PrintStream. (byte stream)
They are all byte streams and are a part of the original Java specification.
They are NOT character streams ! (Unicode character = 2 bytes)
ITP 120 Java Programming I98
Patrick Healy
Class #15 – Input and Output Reading Keyboard Input// Read an array of bytes from the keyboard.
import java.io.*;
public class ReadBytes {
public static void main(String[ ] args)
throws IOException {
byte data[ ] = new byte[10]; // Byte array “data” holds 10 bytes
System.out.println("Enter some characters:");
System.in.read(data); // Use the “read” method to read some bytes
System.out.print("You entered: ");
for(int i=0; i < data.length; i++)
System.out.print((char) data[i]); // Cast data to a character
} // End main method
} // End class ReadBytes
ITP 120 Java Programming I99
Patrick Healy
Class #15 – Input and Output Reading Keyboard Input Here is a sample run from the previous program:
Enter some characters: (prompt from program)
READ BYTES (User entered READ BYTES)
You entered: READ BYTES (output from program)
ITP 120 Java Programming I100
Patrick Healy
Class #15 – Input and Output Writing Output to the Monitor
// Demonstrate System.out.write(). Java program WriteDemo.java
public class WriteDemo
{
public static void main(String[ ] args)
{
int b; // Program prints an ‘X’ on the monitor
b = 'X'; // The character is an int
System.out.write(b); // A byte stream; write low-order 8 bits
System.out.write('\n'); // Print a newline character \n
} // End of main( ) // print() and println() are easier to use than write()
} // End of class WriteDemo
ITP 120 Java Programming I101
Patrick Healy
Class #15 – Input and Output Stream classes (Bytes & Characters) The java.io package provides two categories of classes:
Byte stream readers and writers Character stream readers and writers
At the top of the hierarchy for stream classes are the abstract classes InputStream and Output Stream
The subclasses branch out and specializes into the different types of streams that they handle.
InputData, OutputData, and ObjectInput interfaces are implemented by the classes that handle data, such as, int, double, char, etc., and objects. Only ObjectInput specifies methods for reading objects.
DataInputStream - which is a subclass of FilterInputStream, which in turn is a subclass of InputStream – implements the InputData interface and can read primitive data, and objects from byte streams.
ITP 120 Java Programming I102
Patrick Healy
Class #15 – Input and Output Stream Classes FileInputStream can read raw streams of data from files. DataOutputStream can write primitive data; this class implements the
OutputData interface RandomAccessFile implements both InputData and OutputData
interfaces, therefore, it can read and write data to streams. ObjectOutputStream implements the ObjectOutput interface and can
write object data to streams.
ITP 120 Java Programming I103
Patrick Healy
Class #15 – Input and Output
InputStream Class (for reading bytes)
The following methods are defined in InputStream
and are often useful: public abstract int read() throws IOException
Reads the next byte and returns its value in the range of 0 to 255. At the end of the stream, it returns a - 1.
public int read(byte b[]) throws IOException
Reads bytes into array b,, returns b.length if the number of available bytes is >= b.length. Returns the number of bytes read if the number of available bytes is < than b.length, and returns –1 at the end of the stream.
ITP 120 Java Programming I104
Patrick Healy
Class #15 – Input and Output
InputStream Class (for reading bytes)
The following methods are defined in InputStream and are often useful:
public void close() throws IOException
This method closes the input stream.
public void available() throws IOException
Returns the number of bytes that can be read from the input stream without blocking.
ITP 120 Java Programming I105
Patrick Healy
Class #15 – Input and Output
InputStream Class (for reading bytes)
The following method is defined in InputStream and is often useful:
public long skip(long n) throws IOException
Skip over and discard n bytes of data from the input stream. The actual number of bytes skipped is returned.
ITP 120 Java Programming I106
Patrick Healy
Class #15 – Input and Output Reading & Writing Files Using Byte Streams To create a byte stream linked to a file, use FileInputStream or
FileOutputStream To open a file, create an object of one of these classes, specifying the
name of the file as an argument to the constructor. Once the file is open, you can read from the file or write to the file. To read form a file, you may use the read( ) method.
int read( ) throws IOException When you are done with a file, you should close it by calling close()
void close( ) throws IOException Closing a file releases the system resources allocated to the file,
allowing them to be used by another file.
ITP 120 Java Programming I107
Patrick Healy
Class #15 – Input and Output Reading & Writing Files Using Byte Streams
/* Display a text file.
To use this program, specify the name
of the file that you want to see.
For example, to see a file called TEST.TXT,
use the following command line.
Command line usage: java ShowFile TEST.TXT */
// Program ShowFile.java follows on the next slide ->
ITP 120 Java Programming I108
Patrick Healy
Class #15 – Input and Output Reading & Writing Files Using Byte Streamspublic class ShowFile { public static void main(String[ ] args) throws IOException { int i; FileInputStream fin; // Declare file pointertry { fin = new FileInputStream(args[0]); } // Open the input file catch(FileNotFoundException exc) { System.out.println(“Error: “ + exc.getMessage( )); System.out.println("File Not Found"); return; } } catch(ArrayIndexOutOfBoundsException exc) { System.out.println(“Error: “ + exc.getMessage( )); System.out.println("Usage is: java ShowFile File.txt "); return; }
ITP 120 Java Programming I109
Patrick Healy
Class #15 – Input and Output Reading & Writing Files Using Byte Streams
// Read bytes until EOF is encountered
do {
i = fin.read( ); // Read an integer
if(i != -1) System.out.print((char) i); // Cast the int as a char
} while( i != -1); // When i = -1, EOF is encountered
fin.close( ); // Close the input file
} // End of main method
} // End of class ShowFile
ITP 120 Java Programming I110
Patrick Healy
Class #15 – Input and Output Writing to a File Using Byte Streams
/* Java program to Copy a text file.
To use this program, specify the name
of the source file and the destination file.
For example, to copy a file called File1.txt
to a file called File2.txt , use the following
on the command line:
Usage: java CopyFile File1.txt File2.txt */
ITP 120 Java Programming I111
Patrick Healy
Class #15 – Input and Output Writing to a File Using Byte Streams
// CopyFile.java Demo byte stream file operations
import java.io.*;
public class CopyFile {
public static void main(String[ ] args) throws IOException
{
int i;
FileInputStream fin; // Declare 2 byte stream files (pointers)
FileOutputStream fout; // Output file pointer
ITP 120 Java Programming I112
Patrick Healy
Class #15 – Input and Output Writing to a File Using Byte Streams
try { // outer try block
// try to open input file
try { // inner try
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException exc) {
System.out.println(“Error:”
+ exc.getMessage( ) );
System.out.println("Input File Not Found");
return; }
ITP 120 Java Programming I113
Patrick Healy
Class #15 – Input and Output Writing to a File Using Byte Streams
// open output file
try {
fout = new FileOutputStream(args[1]);
} catch(FileNotFoundException exc) {
System.out.println(“Error: “ + exc.getMessage());
System.out.println("Error Opening Output File");
return;
}
} // End of outer try block
ITP 120 Java Programming I114
Patrick Healy
Class #15 – Input and Output Writing to a File Using Byte Streams catch(ArrayIndexOutOfBoundsException exc) {
System.out.println(“Error: “ + exc.getMessage( ) );
System.out.println("Usage: CopyFile File1 File2");
return; }
try { // Try to copy file1 to file2
do {
i = fin.read( ); // Read a byte
if(i != -1) fout.write(i); // Write the byte to the output file
} while(i != -1); // Loop while not at EOF (-1)
} // End of try block
catch(IOException exc)
{ System.out.println("File Error"); }
fin.close( ); // Close the input file
fout.close( ); // Close the output file
} // End of main( ) method
} // End of class CopyFile
ITP 120 Java Programming I115
Patrick Healy
Class #15 – Input and Output Reading & Writing Binary Data So far, we have been reading and writing bytes containing ASCII bytes. You may want to create a file that contains other types of data such as
integers, doubles, or shorts , that is: int, double, short, etc. In Java, to read and write binary values of the simple Java data types,
you should use:
DataInputStream and DataOutputStream (for binary data)
DataOutputStream implements the OutputData interface. The OutputData interface defines methods that write all of Java’s
simple data types to a file.
ITP 120 Java Programming I116
Patrick Healy
Class #15 – Input and Output Reading & Writing Binary Data Note: Binary data is NOT in human-readable text format, obviously.
The constructor for DataOutputStream is:
DataOutputStream(OutputStream outputStream)
outputStream is the stream to which the binary data is written.
ITP 120 Java Programming I117
Patrick Healy
Class #15 – Input and Output Reading & Writing Binary Data The constructor for DataInputStream is:
DataInputStream(InputStream inputStream)
inputStream is the stream that is linked to the instance of
DataInputStream being created.
DataInputStream implements the DataInput interface which provides the methods for reading all of Java’s simple data types.
DataInputStream uses an InputStream instance as its foundation, overlaying it with methods that read the various Java data types.
ITP 120 Java Programming I118
Patrick Healy
Class #15 – Input and Output Reading & Writing Binary Data Examples
To create an input stream for the file in.dat ( bytes)
DataInputStream infile =
new DataInputStream(new FileInputStream(“in.dat”));
To create an output stream for the file out.dat:
DataOutputStream outfile =
new DataOutputStream(new FileOutputStream(“out.dat”));
ITP 120 Java Programming I119
Patrick Healy
Class #15 – Input and Output Reading & Writing Binary Data Common Input Methods Defined by DataInputStream (a byte stream)
Input Method Purpose
boolean readBoolean ( ) Reads a boolean
byte readByte ( ) Reads a byte
char readChar ( ) Reads a char
double readDouble( ) Reads a double
float readFloat ( ) Reads a float
int readInt ( ) Reads an int
long readLong ( ) Reads a long
short readShort ( ) Reads a short
ITP 120 Java Programming I120
Patrick Healy
Class #15 – Input and Output Reading & Writing Binary Data Common Output Methods Defined by DataOutputStream ( byte stream)
Output Method Purpose
void writeBoolean (boolean val) writes the boolean specified by val
void writeByte (int val) writes the low-order byte val
void writeChar(int val) writes the value val as a char
void writeDouble(double val) writes the double val
void writeFloat(float val) writes the float val
void writeInt(int val) writes the int val
void writeLong(long val) writes the long val
void writeShort(int val) writes val as a short
ITP 120 Java Programming I121
Patrick Healy
Class #15 – Input and Output Reading & Writing Binary Data Here is a Java program that demonstrates DataOutputStream and
DataInputStream. It writes and then reads back various types of data to and from a file.
// Write and then read back binary data.
import java.io.*;
public class RWData {
public static void main(String[ ] args) throws IOException
{
DataOutputStream dataOut; // Declare output, input file pointers
DataInputStream dataIn;
ITP 120 Java Programming I122
Patrick Healy
Class #15 – Input and Output Reading & Writing Binary Data
int i = 120;
double d = 1049.56;
boolean b = true;
try {
dataOut = new
DataOutputStream(new FileOutputStream(“testdata")); }
catch(IOException exc) {
System.out.println(“Error: “ + exc.getMessage( ));
System.out.println("Cannot open file.");
return; }
ITP 120 Java Programming I123
Patrick Healy
Class #15 – Input and Output Reading & Writing Binary Datatry { // Write the binary data
System.out.println("Writing " + i);
dataOut.writeInt(i);
System.out.println("Writing " + d);
dataOut.writeDouble(d);
System.out.println("Writing " + b);
dataOut.writeBoolean(b);
System.out.println("Writing " + 12.2 * 7.4);
dataOut.writeDouble(12.2 * 7.4);
}
ITP 120 Java Programming I124
Patrick Healy
Class #15 – Input and Output Reading & Writing Binary Data catch(IOException exc) {
System.out.println("Write error: + exc.getMessage( )");
}
dataOut.close( );
System.out.println(); // Print a blank line
// Now, read them back.
try {
dataIn = new
DataInputStream(new FileInputStream("testdata"));
}
catch(IOException exc) {
System.out.println("Cannot open file. + exc.getMessage( )");
return;
}
ITP 120 Java Programming I125
Patrick Healy
Class #15 – Input and Output Reading & Writing Binary Data
try { // Read the binary data
i = dataIn.readInt();
System.out.println("Reading " + i);
d = dataIn.readDouble();
System.out.println("Reading " + d);
b = dataIn.readBoolean();
System.out.println("Reading " + b);
d = dataIn.readDouble();
System.out.println("Reading " + d);
}
ITP 120 Java Programming I126
Patrick Healy
Class #15 – Input and Output Reading & Writing Binary Data
catch(IOException exc) {
System.out.println("Read error.“ + exc.getMessage( ) ); }
dataIn.close();
} // End of main ( )
} // End of class RWData
The output from the previous program follows:
Writing 120 Reading 120
Writing 1023.56 Reading 1049.56
Writing true Reading true
Writing 90.28 Reading 90.28
ITP 120 Java Programming I127
Patrick Healy
Class #15 – Input and Output
Reader class methods for reading characters
The Reader class is similar to the InputStream class. The methods in Reader are subject to character interpretation.
Remember: A character is 2 bytes ! public abstract int read() throws IOException
public int read(char b[]) throws IOException
public void close() throws IOException
public void skip() throws IOException
ITP 120 Java Programming I128
Patrick Healy
Class #15 – Input and Output OutputStream ( bytes) & Writer (for characters)
Like InputStream (for reading bytes) and Reader (for reading characters), OutputStream and Writer are the counterparts.
They are the base classes for for all output streams of bytes and characters, respectively.
The next slide shows methods which are in both OutputStream and Writer.
See next slide ->
ITP 120 Java Programming I129
Patrick Healy
Class #15 – Input and Output
OutputStream (Writing bytes)
public abstract void write(int b) throws IOException
Write a byte b (for OutputStream) or a charcter (for Writer)
public void write(byte[] b) throws IOException
This method writes all bytes in the array b to the output stream (for OutputStream) or characters in the array of characters (for Writer)
public void close() throws IOException
This method closes the output stream.
public void flush() throws IOException
Flush the output stream and send any buffered data in the stream to its destination.
ITP 120 Java Programming I130
Patrick Healy
Class #15 – Input and Output Writer (Writing characters) (Same as OutputStream)
public abstract void write(int b) throws IOException
Write a byte b (for OutputStream) or a character (for Writer)
public void write(byte[] b) throws IOException
This method writes all bytes in the array b to the output stream (for OutputStream) or characters in the array of characters (for Writer)
public void close() throws IOException
This method closes the output stream.
public void flush() throws IOException
Flush the output stream and send any buffered data in the stream to its destination.
ITP 120 Java Programming I131
Patrick Healy
Class #15 – Input and Output Console Input using Character Streams
For Java code that will be internationalized, inputting data from the console using Java’s character-based streams is a better, more convenient way to read characters from the keyboard than using byte streams.
Since System.in is a byte-stream, you need to wrap System.in inside of some type of Reader.
The best class for reading console input is BufferedReader which supports a buffered input stream. (BufferedReader inherits from Reader)
But, you cannot construct a BufferedReader directly from System.in
ITP 120 Java Programming I132
Patrick Healy
Class #15 – Input and Output Console Input using Character Streams
You must first convert the input from System.in from a byte stream into a character stream. To do this, you must use InputStreamReader.
InputStreamReader converts bytes to characters.
To obtain an InputStreamReader object that is linked to System.in, use the following constructor:
InputStreamReader ( InputStream inputStream )
Since System.in refers to an object of type InputStream, it can be used for inputStream such as in: InputStreamReader(System.in)
ITP 120 Java Programming I133
Patrick Healy
Class #15 – Input and Output Console Input using Character Streams
Next, using the object produced by InputStreamReader, construct a BufferedReader using the following constructor:
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader being created.
ITP 120 Java Programming I134
Patrick Healy
Class #15 – Input and Output Console Input using Character Streams
Putting it all together, the following line of code creates a BufferReader that is connected to the keyboard.
BufferedReader br =
new BufferedReader( new InputStreamReader(System.in));
After the above statement executes, “br” will be a character-based
stream that is linked to the console thru System.in (which reads bytes)
ITP 120 Java Programming I135
Patrick Healy
Class #15 – Input and Output Console Input using Character Streams Reading Characters
Characters can be read from System.in using the read( ) method defined by BufferedReader.
BufferedReader defines the following versions of read( ) int read( ) throws IOException int read(char data[ ] ) throws IOException int read(char data[ ], int start, int max) throws IOException
ITP 120 Java Programming I136
Patrick Healy
Class #15 – Input and Output Console Input using Character Streams int read( ) throws IOException
reads a single Unicode character and returns a -1 when the end of the stream is reached.
int read(char data[ ]) throws IOException
reads characters from the input stream until:
(1) the array is full, (2) EOF is reached, or (3) an error occurs. int read(char data[ ], int start, int max) throws IOException
reads input into array data beginning at the location specified by start, storing up to max characters. It returns the number of characters read or -1 when the end of the stream is reached.
Pressing the [Enter] key generates an end-of-stream condition.
ITP 120 Java Programming I137
Patrick Healy
Class #15 – Input and Output Console Input using Character Streams The following program demonstrates the read( ) method by reading
characters from the console until the user types a period.
// Use a BufferedReader to read characters from the console.
import java.io.*;
public class ReadChars {
public static void main(String[ ] args) throws IOException
{
ITP 120 Java Programming I138
Patrick Healy
Class #15 – Input and Output Console Input using Character Streams
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter some characters; period to quit.");
// read characters
do {
c = (char) br.read(); // Cast the character to a byte
System.out.println(c); // Print the character
} while(c != '.'); // Loop as long as the input char is not a period
} // End of main method
} // End of ReadChars class
ITP 120 Java Programming I139
Patrick Healy
Class #15 – Input and Output Console Input using Character Streams Output from the previous program could be:
Enter some characters; period to quit.
I
T
P
J
A
V
A
. <- note the period character which stopped the input stream
ITP 120 Java Programming I140
Patrick Healy
Class #15 – Input and Output Console Input using Character Streams Reading Character Strings from the Keyboard …
To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class. The general form is:
String readLine( ) throws IOException
It returns a string object that contains the characters read. It returns null if an attempt is made to read beyond the end of the stream.
ITP 120 Java Programming I141
Patrick Healy
Class #15 – Input and Output Console Input using Character Streams
The following program demonstrates BufferedReader and the readLine() method. The program reads and displays lines of text until the user enters the word “stop”
// Read a string from console using a BufferedReader.
import java.io.*;
class ReadLines {
public static void main(String[ ] args)
throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
ITP 120 Java Programming I142
Patrick Healy
Class #15 – Input and Output Console Input using Character Streams
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop"));
} // End of main method
} // End of class ReadLines
ITP 120 Java Programming I143
Patrick Healy
Class #15 – Input and Output Console Output using Character Streams The preferred method of writing to the console (monitor) when using
Java is through a PrintWriter stream. PrintWriter is one of the character-based classes. Using a character-based class makes it easier to internationalize
Java programs. PrintWriter has several constructors, but this is the one to be used in
the demonstration program which is on the following slides:
PrintWriter(OutputStream outputStream, boolean flushOnNewline)
ITP 120 Java Programming I144
Patrick Healy
Class #15 – Input and Output Console Output using Character Streams
PrintWriter(OutputStream outputStream, boolean flushOnNewline)
Here, outputStream is an object of type OutputStream.
flushOnNewLine controls whether Java flushes the output stream every time a println( ) method is called.
If flushOnNewLine is true flushing automatically takes place.
If flushOnNewLine is false, flushing is not automatic.
ITP 120 Java Programming I145
Patrick Healy
Class #15 – Input and Output Console Output using Character Streams
To write to the console (monitor) using a PrintWriter, specify System.out for the output stream and flush the stream after each call to println( ).
For example, the following line of code creates a PrintWriter that is connected to console (monitor) output.
PrintWriter pw = new PrintWriter(System.out, true);
The Java program on the next slide demonstrates a PrintWriter
ITP 120 Java Programming I146
Patrick Healy
Class #15 – Input and Output Console Output using Character Streams
// Demonstrate PrintWriter.
import java.io.*;
public class PrintWriterDemo {
public static void main(String[ ] args) {
PrintWriter pw = new PrintWriter(System.out, true);
int i = 120;
double d = 123.67;
ITP 120 Java Programming I147
Patrick Healy
Class #15 – Input and Output Console Output using Character Streams
pw.println("Using a PrintWriter."); // PrintWriter Demo
pw.println(i);
pw.println(d);
pw.println(i + " + " + d + " is " + i +d);
} // End of main( ) method
} // End of class PrintWriterDemo
The output from the previous program is:
Using a PrintWriter.
120
123.67
120 + 123.67 is 243.67
ITP 120 Java Programming I148
Patrick Healy
Class #15 – Input and Output File Input & Output using Character Streams
In general, to perform character-based file I/O, you will use the FileReader and FileWriter classes.
Using a FileWriter
FileWriter creates a Writer that you can use to write to a file.
FileWriter is derived from OutputStreamWriter and Writer classes
Commonly used constructors are:
FileWriter (String fileName) throws IOException
FileWriter (String fileName, boolean append) throws IOException
fileName is the full path name of the file. If append is true, then output is appended to the end of the file. Otherwise, the file is overwritten.
ITP 120 Java Programming I149
Patrick Healy
Class #15 – Input and Output File I / O using Character Streams FileWriter
// A simple keyboard-to-disk utility that demonstrates a FileWriter.
import java.io.*;
public class KtoD {
public static void main(String[ ] args)
throws IOException {
String str;
FileWriter fw;
BufferedReader br =
new BufferedReader( new InputStreamReader(System.in));
ITP 120 Java Programming I150
Patrick Healy
Class #15 – Input and Output File I / O using Character Streams FileWriter
try {
fw = new FileWriter("test.txt"); // Try to open the file
}
catch(IOException exc) {
System.out.println(“Error: “ + exc.getMessage( ) );
System.out.println("Cannot open output file.");
return ;
}
ITP 120 Java Programming I151
Patrick Healy
Class #15 – Input and Output File I / O using Character Streams FileWriter
System.out.println("Enter text ('stop' to quit).");
do {
System.out.print(": ");
str = br.readLine( );
if(str.compareTo("stop") == 0) break;
str = str + "\r\n"; // add carriage return & newline
fw.write(str);
} while(str.compareTo("stop") != 0);
fw.close( );
} // End of main ( ) method
} // End of class KtoD
ITP 120 Java Programming I152
Patrick Healy
Class #15 – Input and Output File I / O using Character Streams FileReader
The FileReader class creates a Reader that you can use to read the
contents of a file. FileReader is derived from the InputStreamReader and Reader classes. It has access to the methods in those classes.
The most common constructor is:
FileReader(String fileName) throws FileNotFoundException
where fileName is the full path name of the file.
It throws a FileNotFoundException if the file does not exist.
ITP 120 Java Programming I153
Patrick Healy
Class #15 – Input and Output File I / O using Character Streams FileReader
The following program reads a text file called “test.txt” and displays the information on the screen.
// A simple disk-to-screen utilitiy that demonstrates a FileReader.
import java.io.*;
class DtoS {
public static void main(String[ ] args) throws Exception
{
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
String s;
ITP 120 Java Programming I154
Patrick Healy
Class #15 – Input and Output File I / O using Character Streams FileReader
while((s = br.readLine()) != null)
{
System.out.println(s);
}
fr.close( ); // Close the file
} // End of main( ) method
} // End of DtoS class
ITP 120 Java Programming I155
Patrick Healy
Class #15 – Input and Output
The File Class: Objectives To discover file properties, delete and rename files using the File class To understand how I/O is processed in Java To distinguish between text I/O and binary I/O To read and write characters using FileReader and FileWriter To improve the performance of text I/O using BufferedReader and BufferedWriter To write primitive values, strings, and objects as text using PrintWriter and PrintStream To read and write bytes using FileInputStream and FileOutputStream To read and write primitive values and strings using
DataInputStream/DataOutputStream To store and restore objects using ObjectOutputStream and ObjectInputStream, and to
understand how objects are serialized and what kind of objects can be serialized To use RandomAccessFile for both read and write.
ITP 120 Java Programming I156
Patrick Healy
Class #15 – Input and Output
The File Class
The File class is intended to provide an abstraction that deals with most of the machine-dependent complexities of files and path names in a machine-independent fashion. The filename is a string.
The File class is a wrapper class for the file name and its directory path.
ITP 120 Java Programming I157
Patrick Healy
Class #15 – Input and Output java.io.File
+File(pathname: String)
+File(parent: String, child: String)
+File(parent: File, child: String)
+exists(): boolean
+canRead(): boolean
+canWrite(): boolean
+isDirectory(): boolean
+isFile(): boolean
+isAbsolute(): boolean
+isHidden(): boolean
+getAbsolutePath(): String
+getCanonicalPath(): String
+getName(): String
+getPath(): String
+getParent(): String
+lastModified(): long
+delete(): boolean
+renameTo(dest: File): Boolean
Creates a File object for the specified pathname. The pathname may be a directory or a file.
Creates a File object for the child under the directory parent. child may be a filename or a subdirectory.
Creates a File object for the child under the directory parent. parent is a File object. In the preceding constructor, the parent is a string.
Returns true if the file or the directory represented by the File object exists.
Returns true if the file represented by the File object exists and can be read.
Returns true if the file represented by the File object exists and can be written.
Returns true if the File object represents a directory.
Returns true if the File object represents a file.
Returns true if the File object is created using an absolute path name.
Returns true if the file represented in the File object is hidden. The exact definition of hidden is system-dependent. On Windows, you can mark a file hidden in the File Properties dialog box. On Unix systems, a file is hidden if its name begins with a period character '.'.
Returns the complete absolute file or directory name represented by the File object.
Returns the same as getAbsolutePath() except that it removes redundant names, such as "." and "..", from the pathname, resolves symbolic links (on Unix platforms), and converts drive letters to standard uppercase (on Win32 platforms).
Returns the last name of the complete directory and file name represented by the File object. For example, new File("c:\\book\\test.dat").getName() returns test.dat.
Returns the complete directory and file name represented by the File object. For example, new File("c:\\book\\test.dat").getPath() returns c:\book\test.dat.
Returns the complete parent directory of the current directory or the file represented by the File object. For example, new File("c:\\book\\test.dat").getParent() returns c:\book.
Returns the time that the file was last modified.
Deletes this file. The method returns true if the deletion succeeds.
Renames this file. The method returns true if the operation succeeds.
Obtaining file properties and manipulating file
ITP 120 Java Programming I158
Patrick Healy
Class #15 – Input and Output Example Using the File Class TestFileClass.java
Objective: Write a program that demonstrates how to create files in a platform-independent way and use the methods in the File class to obtain their properties. Figure 1 shows a sample run of the program on Windows, and Figure 2 a sample run on Unix (Windows) (Unix)
ITP 120 Java Programming I159
Patrick Healy
Class #15 – Input and Output The File Class and Processing External Files The File class provides an abstraction that deals with most of the
machine-dependent complexities of files and path names in a machine-independent fashion.
You can create a new File object using the following statement:
File myfile = new File (“myfile.dat”);
You can use the File class to check properties of files, such as whether the file exists, or is readable, or updateable.
ITP 120 Java Programming I160
Patrick Healy
Class #15 – Input and Output The File Class and Processing External Files You can use the getName( ) method to get the name of the file. For example,
if (myfile.exists( ) )
System.out.println(“File “ + myfile.getName( ) + “ already exists”);
The following statement creates a file using the full path using the Windows operating system:
File myfile = new File(“C:\\Java\\myfile.data”);
ITP 120 Java Programming I161
Patrick Healy
Class #15 – Input and Output The File Class and Processing External Files You can use the getPath( ) method to get the full path of the file and
the getParent( ) method to get the directory that contains the file. For example,
if (myfile.exists( ) )
{
System.out.println(“The full path is “ + myfile.getPath( ) );
System.out.println(“The directory is “ + myfile.getParent( ) );
}
ITP 120 Java Programming I162
Patrick Healy
Class #15 – Input and Output Demo Program: TestFileClass.java// TestFileClass.java: Demonstrate the File class Chapt 18 I/O ITP120import java.io.*;import java.util.*;
public class TestFileClass { public static void main(String[] args) { // Create a File object File file = new File(".", "images" + File.separator + "bill_gates.gif"); System.out.println("Does it exist? " + file.exists()); System.out.println("Can it be read? " + file.canRead()); System.out.println("Can it be written? " + file.canRead()); System.out.println("Is it a directory? " + file.isDirectory()); System.out.println("Is it a file? " + file.isFile()); System.out.println("Is it absolute? " + file.isAbsolute()); System.out.println("Is it hidden? " + file.isHidden()); System.out.println("What is its absolute path? " + file.getAbsolutePath());
ITP 120 Java Programming I163
Patrick Healy
Class #15 – Input and Output Demo Program: TestFileClass.java try { System.out.println("What is its canonical path? " + file.getCanonicalPath()); } catch (IOException ex) { }
System.out.println("What is its name? " + file.getName()); System.out.println("What is its path? " + file.getPath()); System.out.println("When was it last modified? " + new Date(file.lastModified()));
System.out.println("What is the path separator? " + File.pathSeparatorChar); System.out.println("What is the name separator? " + File.separatorChar); }}
ITP 120 Java Programming I164
Patrick Healy
Class #15 – Input and Output
Processing External Files
Again, you must use file streams to read from or writeto a disk file.
Once again, you can use FileInputStream or FileOutputStream for byte streams.
And you can use FileReader or FileWriter for character streams.
ITP 120 Java Programming I165
Patrick Healy
Class #15 – Input and Output File I/O Stream Constructors
To create a file stream, use these constructors:
public FileInputStream (String filenameString) // Byte stream constructors
public FileInputStream (File file)
public FileOutputStream (String filenameString) // Byte stream constructor
public FileOutputStream (File file)
public FileReader (String filenameString) // Character stream constructors
public FileReader (File file)
public FileWriter (String filenameString) // Character stream constructor
public FileWriter (File file)
ITP 120 Java Programming I166
Patrick Healy
Class #15 – Input and Output
File I/O Stream Constructors
Constructing instances of FileInputStream, FileOutputStream, FileReader, and FileWriter from file 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");
ITP 120 Java Programming I167
Patrick Healy
Class #15 – Input and Output Demo Program: TestFileReader.java// TestFileReader.java Chapter 18 I/O ITP 120import java.io.*;public class TestFileReader { public static void main(String[ ] args) { FileReader input = null; try { // Create an input stream input = new FileReader("temp.txt"); int code; // Repeatedly read a character and display it on the console while ((code = input.read()) != -1) System.out.print((char)code); } // End of try block
ITP 120 Java Programming I168
Patrick Healy
Class #15 – Input and Output Demo Program: TestFileReader.javaSystem.out.println("File temp.txt does not exist"); } catch (IOException ex) { ex.printStackTrace(); } finally { try { input.close(); // Close the stream } catch (IOException ex) { ex.printStackTrace(); } } } // End of class TestFileReader
ITP 120 Java Programming I169
Patrick Healy
Class #15 – Input and Output Demo Program: TestFileWriter.java// TestFileWriter.java Chapter 18 File I/O ITP 120import java.io.*;
public class TestFileWriter { public static void main(String[ ] args) throws IOException { // Create an output stream to the file FileWriter output = new FileWriter("temp.txt", true);
// Output a string to the file output.write(“ NVCC Introduction to Java Programming ITP 120 !!!");
// Close the stream output.close(); }}
ITP 120 Java Programming I170
Patrick Healy
Class #15 – Input and Output Processing External Files
ITP 120 Java Programming I171
Patrick Healy
Class #15 – Input and Output Processing External Files The previous diagram shows that:
FileInputStream, fis, is used to read data (bytes) from a file
FileOutputStream, fos, is used to write data (bytes) to a file
Command line:
java CopyFileUsingByteStream f1.txt f2.txt
See the Java program CopyFileUsingByteStream on the following slides
ITP 120 Java Programming I172
Patrick Healy
Class #15 – Input and Output Processing External Files
// CopyFileUsingByteStream.java For Copying files (byte streams)
import java.io.*;
public class CopyFileUsingByteStream
{
// Main method: args[0] for sourcefile and args[1] for target file
public static void main(String[ ] args)
{
// Declare input and output file streams
FileInputStream fis = null;
FileOutputStream fos = null;
ITP 120 Java Programming I173
Patrick Healy
Class #15 – Input and Output Processing External Files
if (args.length !=2) // args[0] is source file
{ // args[1] is target file
System.out.println(
"Usage: java CopyFileUsingByteStream f1 f2");
System.exit(0); // Stop the program
}
ITP 120 Java Programming I174
Patrick Healy
Class #15 – Input and Output Processing External Files
try
{
// Create file input stream
fis = new FileInputStream(new File(args[0]));
// Create file output stream if the file does not exist
File outFile = new File(args[1]);
if (outFile.exists())
{
System.out.println("file " + args[1] + " already exists");
return;
}
ITP 120 Java Programming I175
Patrick Healy
Class #15 – Input and Output Processing External Files
else
fos = new FileOutputStream(args[1]); // FileOutputStream
// Display the file size
System.out.println("The file " + args[0] + " has "+
fis.available() + " bytes");
ITP 120 Java Programming I176
Patrick Healy
Class #15 – Input and Output Processing External Files
// Continuously read a byte from fis and write it to fos
int r;
while ((r = fis.read()) != -1) // EOF is -1
fos.write((byte)r);
}
catch (FileNotFoundException ex)
{
System.out.println(“Error: “ + ex.getMessage( ) );
System.out.println("File not found: " + args[0]);
}
ITP 120 Java Programming I177
Patrick Healy
Class #15 – Input and Output Processing External Files
catch (IOException ex)
{
System.out.println(“Some IO Exception occurred”);
System.out.println(“Error: “ + ex.getMessage( ));
}
Continues to next slide
ITP 120 Java Programming I178
Patrick Healy
Class #15 – Input and Output Processing External Files finally
{
try
{
if (fis != null) fis.close(); // Close the input & output files
if (fos != null) fos.close();
}
catch (IOException ex)
{
System.out.println(“Error: “ + ex.getMessage( ) );
}
} // End of finally block
} // End of main method
} // End of class CopyFileUsingByteStream
ITP 120 Java Programming I179
Patrick Healy
Class #15 – Input and Output Filter Streams
Filter streams are streams that filter bytes or characters for some purpose.
If you want to read integers, doubles, or Strings, you need a filter class to wrap the input stream.
Using a filter class enables you to read integers, doubles, and strings instead of bytes and characters.
Use FilterInputStream and FilterOutputStream when you need to process primitive numeric types.
ITP 120 Java Programming I180
Patrick Healy
Class #15 – Input and Output Filter Streams To process strings, use BufferedReader and PushbackReader to filter
characters.
Note: FilterInputStream and FilterOutputStream are abstract classes.
ITP 120 Java Programming I181
Patrick Healy
Class #15 – Input and Output FilterInputStream subclasses DataInputStream handles binary formats for all primitive data types.
BufferedInputStream gets data from the buffer and then reads them from the stream if necessary.
LineNumberInputStream keeps track of how many lines are read.
PushBackInputStream allows single-byte look-a-head. Looks at a byte and pushes it back to the stream if the byte read is NOT the desired byte.
ITP 120 Java Programming I182
Patrick Healy
Class #15 – Input and Output FilterOutputStream subclasses
DataOutputStream outputs the binary formats for all primitive data types which is useful if another program uses the output.
BufferedOutputStream outputs to the buffer first and then to the stream if necessary. You may also call the flush( ) method to write the buffer to the stream.
PrintStream outputs the Unicode format of all primitive types which is useful if the format is output to the console.
ITP 120 Java Programming I183
Patrick Healy
Class #15 – Input and Output
Data Streams (bytes)
The data streams (DataInputStream and DataOutputStream)
read and write Java primitive types in a machine-independent
fashion.
This enables you to write a data file for one computer
and read it on another computer that has a different operating system or file structure.
ITP 120 Java Programming I184
Patrick Healy
Class #15 – Input and Output DataInputStream Methods defined in the DataInput Interface
int readByte() throws IOException
int readShort() throws IOException
int readInt() throws IOException
int readLong() throws IOException
float readFloat() throws IOException
double readDouble() throws IOException
char readChar() throws IOException
boolean readBoolean() throws IOException
String readUTF() throws IOException
ITP 120 Java Programming I185
Patrick Healy
Class #15 – Input and Output DataOutputStream Methods defined in the DataOutput interface
void writeByte(byte b) throws IOException
void writeShort(short is) throws IOException
void writeInt(int i) throws IOException
void writeLong(long l) throws IOException
void writeFloat(float f) throws IOException
void writeDouble(double d) throws IOException
void writeChar(char c) throws IOException
void writeBoolean(boolean b) throws IOException
void writeBytes(String s) throws IOException
void writeChars(String s) throws IOException
void writeUTF(String s) throws IOException
ITP 120 Java Programming I186
Patrick Healy
Class #15 – Input and Output
DataInputStream & DataOutput Stream Constructors
Data streams are used as wrappers on existing input and output streams to filter data in the original stream.
DataInputStream infile = newDataInputStream(new FileInputStream("in.dat"));
The above creates an input file for in.dat.
DataOutputStream outfile = newDataOutputStream(new FileOutputStream("out.dat"));
The above creates an output file for out.dat.
ITP 120 Java Programming I187
Patrick Healy
Class #15 – Input and Output Using Data Streams
The next example shows a program that:
1) Creates 10 random integers,
2) Stores them in a data file,
3) Retrieves data from the file,
4) Displays the integers on the console.
See next slide
ITP 120 Java Programming I188
Patrick Healy
Class #15 – Input and Output Using Data Streams Demo Example
// TestDataStreams.java: Create a file, store it in binary form, and
// display the contents of the file on the console
import java.io.*;
public class TestDataStreams
{
// Main method
public static void main(String[ ] args)
{
// Declare data input and output streams
DataInputStream dis = null;
DataOutputStream dos = null;
ITP 120 Java Programming I189
Patrick Healy
Class #15 – Input and Output Using Data Streams Demo Example
// Construct a temp file
File tempFile = new File("mytemp.dat");
// Check if the temp file exists
if (tempFile.exists())
{
System.out.println("The file mytemp.dat already exists,"
+" delete it, rerun the program");
System.exit(0);
}
ITP 120 Java Programming I190
Patrick Healy
Class #15 – Input and Output Using Data Streams Demo Example
// Write data
try
{
// Create data output stream for tempFile
dos = new DataOutputStream(new
FileOutputStream(tempFile));
for (int i=0; i<10; i++)
dos.writeInt((int)(Math.random()*1000));
}
ITP 120 Java Programming I191
Patrick Healy
Class #15 – Input and Output Using Data Streams Demo Example
catch (IOException ex)
{
System.out.println(ex.getMessage( ) );
}
finally
{
try
{
if (dos != null) dos.close( ); // Close the file(s)
}
catch (IOException ex)
{ System.out.println(“Error: “ + ex.getMessage( ) ); }
ITP 120 Java Programming I192
Patrick Healy
Class #15 – Input and Output Using Data Streams Demo Example
// Read data
try
{
// Create data input stream
dis = new DataInputStream(new FileInputStream(tempFile));
for (int i=0; i<10; i++)
System.out.print(" "+dis.readInt ( ) ); // Display the integers
}
ITP 120 Java Programming I193
Patrick Healy
Class #15 – Input and Output Using Data Streams
catch (FileNotFoundException ex)
{
System.out.println("File not found“ + ex.getMessage( ) ););
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
ITP 120 Java Programming I194
Patrick Healy
Class #15 – Input and Output Using Data Streams
finally
{
try
{
if (dis != null) dis.close( ); // Close the file(s)
}
catch (IOException ex)
{
System.out.println(“Error: “ + ex.getMessage( ) ));
}
} // End of finally block
} // End of main method
} // End of class TestDataStreams
ITP 120 Java Programming I195
Patrick Healy
Class #15 – Input and Output Using Data Streams Demo Example The previous Java program TestDataStreams.java creates a
DataInputStream object named “dis” wrapped on FileInputStream and creates a DataOutputStream object “dos” wrapped on FileOutputStream
Conceptually,
Program DataInputStream dis <-- fileInputStream <--mytemp.dat
DataOutputStream dos fileOutputStream mytemp.dat
The program uses a temporary file, mytemp.dat, to store data.
The program creates mytemp.dat if it does not exist and writes 10 random
integers into mytemp.dat. The data in mytemp.dat is in binary format.
ITP 120 Java Programming I196
Patrick Healy
Class #15 – Input and Output Character Classes The classes that handle characters have at the top of their hierarchy,
Reader and Writer The subclasses branch out to provide specialized functionality.
FileReader provides functionality for reading streams of characters from files.
BufferedReader buffers character streams for efficiency
FileWriter for writing character streams to files.
PrintWriter for writing character streams.
ITP 120 Java Programming I197
Patrick Healy
Class #15 – Input and Output File Class
File class provides functionality for working directly with files in the operating system
The File class provides overloaded constructors for creating File objects. A File object can be created by giving the name of the file:
File inputFile = new File(“in.dat”); // Same directory File myInputFile = new File(“C:\\myDirectory\\in.dat”);
A File Object can refer to either a file or directory File theDir = new File(“C:\\myDir”); //File object theDir refers to a directory
Some File class methods: exists() that tests if the named file already exist. mkdir( String st ) for creating directories list() for listing the contents of directories getPath() gets the path of the named file length() returns the file size in bytes
ITP 120 Java Programming I198
Patrick Healy
Class #15 – Input and Output File Class
Example: DirectoryContents.java listing the contents of a directory using File class
import java.io.*;
public class DirectoryContents
{
public static void main(String[ ] args)
{
File myDir = new File(“C:\\");
if(myDir.isDirectory( ) ) {
System.out.println("Contents of directory " + myDir );
String[ ] contents = myDir.list();
for( int I = 0; I < contents.length; I++)
System.out.println(contents[ I ] );
} // End of “if” block
} // End of main method
} // End of class DirectoryContents
ITP 120 Java Programming I199
Patrick Healy
Class #15 – Input and Output Using Java I/O
Many of the methods including constructors of Java.io classes throw exceptions:
The most commonly thrown is IOException. Reading data from the keyboard
BufferedReader in = new BufferedReader(new InputStreamReader(System.in); An InputStreamReader is like an adapter, it reads byte streams
and converts it into character streams BufferedReader wraps the InputStreamReader to provide extra
functionality, allowing to buffer the input to support readLine()
ITP 120 Java Programming I200
Patrick Healy
Class #15 – Input and Output Using Java I/O
Example Reading strings from the keyboard
Import java.io.*
public class ReadStringFromKeyboard {
public static void main(String[ ] args)
{ // Converts from bytes to characters
BufferedReader in = new BufferedReader(new InputStreamReader (System.in));
String yourInput;
try {
System.out.println("Please enter any string and hit the return key when done:");
yourInput = in.readLine( );
System.out.println("\nBelow is the input you entered");
System.out.println(yourInput);
}
catch (IOException ex) { System.out.println(“Could not read from the keyboard” }
} // End of main method
} // End of class ReadStringFromKeyboard
ITP 120 Java Programming I201
Patrick Healy
Class #15 – Input and Output Using Java I/O
Example: Reading from an external filepublic class ReadFromFile {
public static void main(String[ ] args)
{
String st = null;
File inputFileName = null;
FileReader inputFile = null;
BufferedReader in = null;
try {
inputFileName = new File("Input1.txt");
inputFile = new FileReader(inputFileName);
in = new BufferedReader(inputFile);
/* Note: The above 3 lines can be combined in one line as below
in = new BufferedReader(new FileReader(new File("Input1.txt"))); */
ITP 120 Java Programming I202
Patrick Healy
Class #15 – Input and Output Using Java I/O
Example Continued // Now let us start reading from the opened file
while((st = br.readLine()) != null )
{
System.out.println(st); // Print the string
}
}
catch (FileNotFoundException fnex)
{ System.out.println(“Error: “ + fnex.getMessage( ) );
System.out.println("Input file was not found");
}
catch (IOException ex) { System.out.println(“Error: “ + ex.getMessage( ) );
System.out.println("There was a problem reading from the file");
}
ITP 120 Java Programming I203
Patrick Healy
Class #15 – Input and Output Using Java I/O Example continuedfinally
{
if( br != null)
try {
br.close( ); // Close the file
}
catch (Exception ex) {
System.out.println(“Error: “ + ex.getMessage( ) );
System.out.println("There was a problem with closing the file");
}
} // End finally block
} // End of main method
} // End of class
ITP 120 Java Programming I204
Patrick Healy
Class #15 – Input and Output
Print Streams
The data output stream outputs a binary representation of data, so you cannot view its contents as text.
In Java, you can use print streams to output data into files. These files can then be viewed as text.
The PrintStream and PrintWriter classes provide the functionality for doing this.
PrintStream is for bytes
PrintWriter is for characters (Unicode)
ITP 120 Java Programming I205
Patrick Healy
Class #15 – Input and Output
Print Streams: PrintWriter Constructors
PrintWriter(Writer out)
PrintWriter(Writer out, boolean autoFlush)
PrintWriter(OutputStream out)
PrintWriter(OutputStream out, boolean autoFlush)
ITP 120 Java Programming I206
Patrick Healy
Class #15 – Input and Output
Print Streams: PrintWriter Methods (for chars)
void print(Object o) void print(String s) void println(String s) void print(char c) void print(char[] cArray) void print(int i) void print(long l) void print(float f) void print(double d) void print(boolean b)
ITP 120 Java Programming I207
Patrick Healy
Class #15 – Input and Output Print Streams: PrintWriter Methods Note:
On the previous slide, you may replace print with println in the various method definitions.
The println method, which prints the object, is followed by a new line.
When the object is passed to print or println,
the object’s toString( ) method converts it to a String object.
ITP 120 Java Programming I208
Patrick Healy
Class #15 – Input and Output Demo Program Example Using Print Streams The next sample Java program creates a print stream, pw, of
PrintWriter, wrapped on FileOutputStream, for text format.
pw = new PrintWriter(new FileOutputStream(tempFile),true);
The program creates the file, arg[0], if that file does not already exist. The program writes 10 random integers into the file by using the data
output stream, then closes the stream. The data file could be viewed by using the type command in DOS
ITP 120 Java Programming I209
Patrick Healy
Class #15 – Input and Output Using Print Streams: Demo Example
// TestPrintWriters.java: Create a text file
// using PrintWriter
import java.io.*;
public class TestPrintWriters
{
// Main method: args[0] is the output file
public static void main(String[] args)
{
// Declare print stream
PrintWriter pw = null;
ITP 120 Java Programming I210
Patrick Healy
Class #15 – Input and Output Using Print Streams: Demo example
// Check usage
if (args.length != 1)
{
System.out.println("Usage: java
TestPrintWriters file");
System.exit(0);
}
File tempFile = new File(args[0]);
ITP 120 Java Programming I211
Patrick Healy
Class #15 – Input and Output Using Print Streams: Demo Example
if (tempFile.exists())
{
System.out.println("The file " + args[0] +
" already exists, delete it, rerun the program");
System.exit(0);
}
ITP 120 Java Programming I212
Patrick Healy
Class #15 – Input and Output Using Print Streams: Demo Example
// Write data
try
{
// Create print writer stream for tempFile
pw = new PrintWriter(new FileOutputStream(tempFile), true);
for (int i=0; i<10; i++)
pw.print(" "+(int)(Math.random()*1000));
}
ITP 120 Java Programming I213
Patrick Healy
Class #15 – Input and Output Using Print Streams: Demo Example
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
finally
{
// Close files
if (pw != null) pw.close();
}
}
}
ITP 120 Java Programming I214
Patrick Healy
Class #15 – Input and Output Using Print Streams: Demo Example
C:\test>java TestPrintWriters
Usage: java TestPrintWriters filename
C:\test>java TestPrintWriters test.dat
C:\test>type test.dat (Use the TYPE command to see data in file)
567 915 7 23 677 455 402 997 290 549
ITP 120 Java Programming I215
Patrick Healy
Class #15 – Input and Output
Print Streams
ITP 120 Java Programming I216
Patrick Healy
Class #15 – Input and Output Using Java I/O
Example: WriteToFile.java Writing text to external files
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
public class WriteToFile {
public WriteToFile( )
{ } // Empty constructor
ITP 120 Java Programming I217
Patrick Healy
Class #15 – Input and Output Using Java I/O
Example: WriteToFile.java (continued)
public static void main (String[ ] args)
{
File outputFileName = null;
PrintWriter outToFile = null;
try {
outputFileName = new File("outFile1.txt");
outToFile = new PrintWriter( new FileWriter(outputFileName));
// Now we can start writing to file
outToFile.println("This message is going to the output file");
outToFile.println("This will be line two in the output file");
outToFile.println("We can write the output file any time we want");
outToFile.flush( ); // Flush output file
}
ITP 120 Java Programming I218
Patrick Healy
Class #15 – Input and Output Using Java I/O Example 18.6
catch (IOException ex) {
System.out.println(“Error: “ + ex.getMessage( ) );
System.out.println("There was a problem writing to the output file");
}
finally {
if ( outToFile != null )
outToFile.close( ); // Close output file
} // End of finally block
} // End of main method
} // End of class WriteToFile
ITP 120 Java Programming I219
Patrick Healy
Class #15 – Input and Output
Buffered Streams in Java
Java introduces buffered streams that speed up input and output by reducing the number of reads and writes. In the case of input, a bunch of data is read all at once instead of one byte at a time.
In the case of output, data are first cached into a buffer, then written all together to the file.
Using buffered streams is highly recommended.
ITP 120 Java Programming I220
Patrick Healy
Class #15 – Input and Output
Buffered Stream Constructors
BufferedInputStream (InputStream in)
BufferedInputStream (InputStream in, int bufferSize)
BufferedOutputStream (OutputStream in)
BufferedOutputStream (OutputStream in, int bufferSize)
BufferedReader(Reader in)
BufferedReader(Reader in, int bufferSize)
BufferedWriter(Writer out)
BufferedWriter(Writer out, int bufferSize)
ITP 120 Java Programming I221
Patrick Healy
Class #15 – Input and Output Demo Program: ViewFile.java (A Text Viewer program)
This case study writes a program that views a text file in a text area. The user enters a filename in a text field and clicks the View button; the file is then displayed in a text area.
ITP 120 Java Programming I222
Patrick Healy
Class #15 – Input and Output Buffered Streams in Java ViewFile program
// ViewFile.java: Read a text file and store it in a text area
import java.awt.*; // Buffered I/O example (Demo program)
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class ViewFile extends MyFrameWithExitHandling
implements ActionListener
{
// Button to view view
private JButton jbtView = new JButton("View");
ITP 120 Java Programming I223
Patrick Healy
Class #15 – Input and Output Buffered Streams in Java ViewFile program
// Text field to receive file name
private JTextField jtf = new JTextField(12);
// Text area to display file
private JTextArea jta = new JTextArea();
public static void main(String [ ] args) // Main method
{
ViewFile frame = new ViewFile();
frame.setTitle("View File Program in Java");
frame.setSize(400, 300);
frame.setVisible(true);
}
ITP 120 Java Programming I224
Patrick Healy
Class #15 – Input and Output Buffered Streams in Java ViewFile program
// Constructor
public ViewFile()
{
// Panel p to hold a label, a text field, and a button
Panel p = new Panel();
p.setLayout(new BorderLayout());
p.add(new Label("Filename"), BorderLayout.WEST);
p.add(jtf, BorderLayout.CENTER);
jtf.setBackground(Color.yellow);
jtf.setForeground(Color.red);
p.add(jbtView, BorderLayout.EAST);
ITP 120 Java Programming I225
Patrick Healy
Class #15 – Input and Output Buffered Streams in Java ViewFile program
// Add jtaFile to a scroll pane
JScrollPane jsp = new JScrollPane(jtaFile);
// Add jsp and p to the frame
getContentPane().add(jsp, BorderLayout.CENTER);
getContentPane().add(p, BorderLayout.SOUTH);
// Register listener
jbtView.addActionListener(this);
}
ITP 120 Java Programming I226
Patrick Healy
Class #15 – Input and Output Buffered Streams in Java ViewFile program
// Handle the "View" button
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == jbtView)
showFile();
}
ITP 120 Java Programming I227
Patrick Healy
Class #15 – Input and Output Buffered Streams in Java ViewFile program
// Display the file in the text area
private void showFile()
{
// Use a BufferedStream to read text from the file
BufferedReader infile = null;
// Get file name from the input text field at the bottom
String filename = jtf.getText().trim();
String inLine;
ITP 120 Java Programming I228
Patrick Healy
Class #15 – Input and Output Buffered Streams in Java ViewFile program
try
{
// Create a buffered stream
infile = new BufferedReader(new FileReader(filename));
// Read a line
inLine = infile.readLine();
boolean firstLine = true;
ITP 120 Java Programming I229
Patrick Healy
Class #15 – Input and Output Buffered Streams in Java ViewFile program
while (inLine != null) // Append the line to the text area
{
if (firstLine) {
firstLine = false;
jtaFile.append(inLine); }
else
{
jta.append("\n" + inLine); }
inLine = infile.readLine();
}
} // End of try block
ITP 120 Java Programming I230
Patrick Healy
Class #15 – Input and Output Buffered Streams in Java ViewFile program
catch (FileNotFoundException ex)
{ System.out.println(“Error: “ + ex.getMessage( ) );
System.out.println("File not found: " + filename);
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
ITP 120 Java Programming I231
Patrick Healy
Class #15 – Input and Output Buffered Streams in Java ViewFile program
finally
{
try
{
if (infile != null) infile.close( ); // Close input file
}
catch (IOException ex)
{
System.out.println(“Error: “ + ex.getMessage( ));
}
} // End of finally block
} // End of method showFile()
} // End of class ViewFile
ITP 120 Java Programming I232
Patrick Healy
Class #15 – Input and Output Buffered Streams in Java ViewFile program
Demostrate the ViewFile program by running:
java ViewFile (at the command prompt)
Wait for Java window to appear.
then type Comcast1.txt or the name of some text file in the text box at the bottom of the Java window.
Look at the contents on the text file in the Java window.
ITP 120 Java Programming I233
Patrick Healy
Class #15 – Input and Output Text Input & Output on the Console
In previous chapters, you used text input and output with the System class. The System class, as you have already seen, contains 3 I/O objects: System.in, System.out, and System.err. The objects in, out and err are static variables.
The variable in is of InputStream type and out , err are of PrintStream type. (byte streams)
These are the basic objects that all java programmers use to get input from the keyboard, send output to the screen, and display error messages.
ITP 120 Java Programming I234
Patrick Healy
Class #15 – Input and Output Text Input & Output on the Console
To perform console output, you can use any of the methods for PrintStream in the System.out object.
To get input from the keyboard, you can use the following statements to read a string from the keyboard
See next slide
AND ALSO VIEW THE EXPANDED VERSION of MyInput.java which
follows thereafter
ITP 120 Java Programming I235
Patrick Healy
Class #15 – Input and Output Text Input & Output on the Console
BufferedReader br
= new BufferedReader(new InputStreamReader(System.in), 1);
// Note: the 1 above means a buffer size of 1
// Declare and initialize the string
String string = " ";
// Get the string from the keyboard
try
{ string = br.readLine(); }
catch (IOException ex) {
System.out.println(ex); }
ITP 120 Java Programming I236
Patrick Healy
Class #15 – Input and Output Text I/O on the Console MyInput.java (full)
public class MyInput // Expanded version
{ // Read a string from the keyboard
public static String readString()
{
BufferedReader br
= new BufferedReader(new InputStreamReader(System.in), 1);
// Declare and initialize the string
String string = " ";
// Get the string from the keyboard
try {
string = br.readLine(); }
catch (IOException ex) {
System.out.println(ex) ; }
ITP 120 Java Programming I237
Patrick Healy
Class #15 – Input and Output Text I/O on the Console MyInput.java (full)
// Return the string obtained from the keyboard
return string;
}
// Read an int value from the keyboard
public static int readInt()
{
return Integer.parseInt(readString());
}
ITP 120 Java Programming I238
Patrick Healy
Class #15 – Input and Output Text I/O on the Console MyInput.java (full)
// Read a double value from the keyboard
public static double readDouble()
{
return Double.parseDouble(readString());
}
// Read a byte value from the keyboard
public static double readByte()
{
return Byte.parseByte(readString());
}
ITP 120 Java Programming I239
Patrick Healy
Class #15 – Input and Output Text I/O on the Console MyInput.java (full)
// Read a short value from the keyboard
public static double readShort()
{
return Short.parseShort(readString());
}
// Read a long value from the keyboard
public static double readLong()
{
return Long.parseLong(readString());
}
ITP 120 Java Programming I240
Patrick Healy
Class #15 – Input and Output Text I/O on the Console MyInput.java (full)
// Read a float value from the keyboard
public static double readFloat()
{
return Float.parseFloat(readString());
}
}
ITP 120 Java Programming I241
Patrick Healy
Class #15 – Input and Output Random Access Files (byte streams) Java allows you to access the contents of a file in random order To do this, you will use RandomAccessFile which encapsulates a
random-access file. RandomAccessFile is a stream class derived from Object RandomAccessFile is NOT derived from InputStream or OutputStream. RandomAccessFile implements interfaces InputData & OutputData InputData & OutputData define the basic I/O methods. You can also position the file pointer within the file using the method
seek ( )
ITP 120 Java Programming I242
Patrick Healy
Class #15 – Input and Output Random Access Files (Constructor(s)) The constructor for RandomAccessFile is:
RandomAccessFile (String filename, String access)
throws FileNotFoundException
The name of the file is passed in filename
The term access determines what type of file access is permitted.
If the access is “r”, the file is read-only.
If the access is “rw”, the file is opened in read-write mode.
ITP 120 Java Programming I243
Patrick Healy
Class #15 – Input and Output Random Access Files (Methods) The method seek ( ) is used to set the current position of the file
pointer within a random access file:
void seek (long newpos) throws IOException
newpos specifies the new position, in bytes, of the file pointer from
the beginning of the file.
After a call to seek( ), the next read or write operation will occur at the
new file position.
ITP 120 Java Programming I244
Patrick Healy
Class #15 – Input and Output Random Access Files (Methods) public long getFilePointer ( ) throws IOException
Returns the offset, in bytes, from the beginning of the file to where the next read or write occurs.
public long length ( ) throws IOException
Returns the length of the file in bytes.
public final void writeChar (int v) throws IOException
Writes a character to the file as a 2-byte Unicode character with the higher byte written first.
public final void writeChars(String s) throws IOException
Writes a string to a file as a sequence of characters.
ITP 120 Java Programming I245
Patrick Healy
Class #15 – Input and Output Random Access Files RandomAccessFile implements the read ( ) and write ( ) methods.
It also implements the InputData and OutputData interfaces, which means that methods to read and write the simple data types such as readInt( ) and writeDouble( ) are available.
The slides which follow show a Java program that demonstrates random
access file I/O. The program writes 6 double numbers to a file and
then reads them back in a non-sequential order.
ITP 120 Java Programming I246
Patrick Healy
Class #15 – Input and Output Random Access Files
// Demonstrate random access files RandonAccessDemo.java
import java.io.*;
public class RandomAccessDemo {
public static void main(String[ ] args)
throws IOException {
double data[ ] = { 19.4, 10.1, 123.54, 33.0, 87.9, 74.25 };
double d;
RandomAccessFile raf;
ITP 120 Java Programming I247
Patrick Healy
Class #15 – Input and Output Random Access Files
try {
raf = new RandomAccessFile("random.dat", "rw");
}
catch(FileNotFoundException ex)
{
System.out.println("Cannot open file.");
System.out.println(“Error: “ + ex.getMessage( ) );
return ;
}
ITP 120 Java Programming I248
Patrick Healy
Class #15 – Input and Output Random Access Files
// Write values to the file.
for (int i=0; i < data.length; i++) {
try {
raf.writeDouble(data[i]);
}
catch(IOException ex) {
System.out.println(“Error: “ + ex.getMessage( ));
System.out.println("Error writing to file.");
return ; }
} // End of “for” loop
ITP 120 Java Programming I249
Patrick Healy
Class #15 – Input and Output Random Access Files
try {
// Now, read back specific values
raf.seek(0); // seek to first double
d = raf.readDouble();
System.out.println("First value is " + d);
raf.seek(8); // seek to second double
d = raf.readDouble();
System.out.println("Second value is " + d);
raf.seek(8 * 3); // seek to fourth double
d = raf.readDouble();
System.out.println("Fourth value is " + d);
System.out.println();
ITP 120 Java Programming I250
Patrick Healy
Class #15 – Input and Output Random Access Files
// Now, read every other value.
System.out.println("Here is every other value: ");
for (int i=0; i < data.length; i+=2) {
raf.seek(8 * i); // seek to ith double
d = raf.readDouble();
System.out.print(d + " ");
} // End of “for” loop
} // End of try block
ITP 120 Java Programming I251
Patrick Healy
Class #15 – Input and Output Random Access Files
catch(IOException exc)
{
System.out.println(“Error: “ + exc.getMessage( ) );
System.out.println("Error seeking or reading.");
}
raf.close( ); // Close the file
} // End of main ( )
} // End of class RandomAccessDemo
ITP 120 Java Programming I252
Patrick Healy
Class #15 – Input and Output Random Access Files Output from the previous Java program RandomAccessDemo:
First value is 19.4
Second value is 10.1
Fourth value is 33.0
Here is every other value:
19.4 123.54 87.9
ITP 120 Java Programming I253
Patrick Healy
Class #15 – Input and Output Case Studies: Address Book
Now let us use RandomAccessFile to create a useful project for storing and viewing and address book. The user interface of the program is shown in Figure 16.24. The Add button stores a new address to the end of the file. The First, Next, Previous, and Last buttons retrieve the first, next, previous, and last addresses from the file, respectively.
ITP 120 Java Programming I254
Patrick Healy
Class #15 – Input and Output
Parsing Text Files
The StreamTokenizer class lets you take an input stream and parse it into words, which are known as tokens.
The tokens are read one at a time.
The following is the StreamTokenizer constructor:
StreamTokenizer st = StreamTokenizer(Reader is)
ITP 120 Java Programming I255
Patrick Healy
Class #15 – Input and Output
StreamTokenizer Constants
TT_WORD
The token is a word.
TT_NUMBER
The token is a number.
TT_EOL
The end of the line has been read.
TT_EOF
The end of the file has been read.
ITP 120 Java Programming I256
Patrick Healy
Class #15 – Input and Output
StreamTokenizer Variables
int ttype (token type)
Contains the current token type, which matches one of the constants listed on the preceding slide.
double nval
Contains the value of the current token if that token is a number.
String sval
Contains a string that gives thecharacters of the current token if thattoken is a word.
ITP 120 Java Programming I257
Patrick Healy
Class #15 – Input and Output
StreamTokenizer Methods
public int nextToken() throws IOException
Parses the next token from the input stream of this StreamTokenizer.
The type of the next token is returned in the ttypefield.
If ttype == TT_WORD, the token is stored in sval;
if ttype == TT_NUMBER, the token is stored in nval.
ITP 120 Java Programming I258
Patrick Healy
Class #15 – Input and Output
Example : Demo program Using StreamTokenizer Demo: ParsingTextFile.java
ITP 120 Java Programming I259
Patrick Healy
Class #15 – Input and Output ParsingTextFile.java (Demo program)// ParsingTextFile.java: ITP 120// Process text file using StreamTokenizer Chapter 18 I/Oimport java.io.*;
public class ParsingTextFile{ // Main method public static void main(String[] args) { // Declare file reader and writer character (2 bytes) streams FileReader frs = null; FileWriter fws = null;
// Declare streamTokenizer StreamTokenizer in = null;
ITP 120 Java Programming I260
Patrick Healy
Class #15 – Input and Output ParsingTextFile.java (Demo)
// Declare a print stream PrintWriter out = null;
// For input file fields: student name, midterm1, // midterm2, and final exam score String sname = null; double midterm1 = 0; double midterm2 = 0; double finalScore = 0;
// Computed total score double total = 0;
try { // Create file input and output streams frs = new FileReader("grades.dat"); fws = new FileWriter("gradesout.dat");
ITP 120 Java Programming I261
Patrick Healy
Class #15 – Input and Output ParsingTextFile.java (Demo)
// Create a stream tokenizer wrapping file input stream in = new StreamTokenizer(frs); out = new PrintWriter(fws); // Create PrintWriter object
// Read first token in.nextToken();
// Process a record // TTs are Tokenizer constants while (in.ttype != in.TT_EOF) // TT_EOF means end of file { // Get student name if (in.ttype == in.TT_WORD) // TT_WORD means token is a word sname = in.sval; else System.out.println("Bad file format");
ITP 120 Java Programming I262
Patrick Healy
Class #15 – Input and Output ParsingTextFile.java (Demo)
// Get midterm1 if (in.nextToken() == in.TT_NUMBER) //TT_NUMBER means token is a number midterm1 = in.nval; else System.out.println("Bad file format");
// Get midterm2 score if (in.nextToken() == in.TT_NUMBER) midterm2 = in.nval; else System.out.println("Bad file format");
// Get final exam score if (in.nextToken() == in.TT_NUMBER) finalScore = in.nval;
ITP 120 Java Programming I263
Patrick Healy
Class #15 – Input and Output ParsingTextFile.java (Demo)
total = midterm1*0.3 + midterm2*0.3 + finalScore*0.4; out.println(sname + " " + total);
in.nextToken( ); } } catch (FileNotFoundException ex) { System.out.println("Error: " + ex.getMessage()); System.out.println("File not found: in.dat"); } catch (IOException ex) { System.out.println(ex.getMessage()); }
ITP 120 Java Programming I264
Patrick Healy
Class #15 – Input and Output ParsingTextFile.java (Demo)
finally // Always execute finally block { try { if (frs != null) frs.close(); if (fws != null) fws.close(); } catch (IOException ex) { System.out.println(ex); } } System.out.println("To view input file, TYPE GRADES.DAT"); System.out.println("To view output file, TYPE GRADESOUT.DAT"); } // End of main method} // End of class
ITP 120 Java Programming I265
Patrick Healy
Class #15 – Input and Output Chapter 18 Demo Programs
ReadBytes.java
WriteDemo.java
ShowFile.java
CopyFile.java CopyFileUsingByteStream.java
CompFile.java
RWData.java
RandomAccessDemo.java
PrintWriterDemo.java
ReadChars.java
ReadLines.java
ITP 120 Java Programming I266
Patrick Healy
Class #15 – Input and Output Chapter 18 Demo Programs
TestDataStreams.java
TestFileClass.java
TestPrintWriters.java
ViewFile.java (cute file viewer program)
ParsingTextFile.java
TestRandomAccessFile.java needs these class files: AddressBook.java FixedLengthStringIO.class
ITP 120 Java Programming I267
Patrick Healy
Class #15 – Input and Output Chapter 18 Demo Programs
TestDataStream.java
TestFileClass.java
TestFileReader.java
TestFileStream.java
TestFileWriter.java
TestObjectStreamForArray.java
TestObjectInputStream.java
TestObjectOutputStream.java
AddressBook.java (with FixedLengthStringIO.java)
Other created or required files: object.dat, temp.txt, student.dat
ITP 120 Java Programming I268
Patrick Healy
Class #15 – Input and Output End of Presentation