liang,introduction to java programming,revised by dai-kaiyu 1 chapter 16 simple input and output...

65
Liang,Introduction to Java Programming,revised by D ai-kaiyu 1 Chapter 16 Simple Input and Output Prerequisites for Part IV Chapter8 Inheritance and Polym orphism Chapter16 Sim ple Inputand O utput Chapter15 Exceptionsand A ssertions 与与与与 与与与与

Upload: barnard-carroll

Post on 12-Jan-2016

244 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu1

Chapter 16 Simple Input and Output

Prerequisites for Part IV

Chapter 8 Inheritance and Polymorphism

Chapter 16 Simple Input and Output

Chapter 15 Exceptions and Assertions

与人玫瑰,手有余香

Page 2: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu2

Objectives To discover file properties, delete and rename files using the File class (§16.2). To understand how I/O is processed in Java (§16.3). To distinguish between text I/O and binary I/O (§16.3). To read and write characters using FileReader and FileWriter (§16.4). To improve the performance of text I/O using BufferedReader and

BufferedWriter (§16.4). To write primitive values, strings, and objects as text using PrintWriter and

PrintStream (§16.4). To read and write bytes using FileInputStream and FileOutputStream (§16.6). To read and write primitive values and strings using

DataInputStream/DataOutputStream (§16.6). To store and restore objects using ObjectOutputStream and ObjectInputStream,

and to understand how objects are serialized and what kind of objects can be serialized (§16.9 Optional).

To use the Serializable interface to enable objects to be serializable (§16.9 Optional).

To use RandomAccessFile for both read and write. (§16.10 Optional)

Page 3: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu3

Introduction

Files Long-term storage of large amounts of data Persistent data exists after termination of program Files stored on secondary storage devices

Magnetic disks Optical disks Magnetic tapes

Sequential and random access files

Page 4: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu4

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.

Page 5: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu5

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

Page 6: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu6

Example 16.1 Using the File Class

TestFileClassTestFileClass RunRun

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 16.1 shows a sample run of the program on Windows, and Figure 16.2 a sample run on Unix.

Page 7: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu7

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.

Program

Input object created from an

input class

Output object created from an

output class

Input stream

Output stream

File

File

FileWriter output = new FileWriter("temp.txt"); output.write("Java 101"); output.close();

FileReader input = new FileReader("temp.txt");int code = input.read(); System.out.println((char)code); Return the

unicode of the char

Page 8: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu8

Coding Essentials

public static void main(String[] args) throws IOException { FileWriter output = new FileWriter("temp.txt"); output.write("Java 101"); output.close(); FileReader input = new FileReader("temp.txt"); int code = input.read(); System.out.println((char)code); input.close(); }

Declaring exception in the method

public static void main(String[] args) { try { FileWriter output = new FileWriter("temp.txt"); output.write("Java 101"); output.close(); FileReader input = new FileReader("temp.txt"); int code = input.read(); System.out.println((char)code); input.close(); } catch (IOException ex) { ex.printStackTrace(); } }

Using try-catch block

Page 9: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu9

Text File vs. Binary File 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.

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.

Page 10: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu10

Text I/O Classes

Reader

Writer

Object

PrintWriter

BufferedWriter

FileReader

FileWriter

InputStreamReader

BufferedReader

OutputStreamWriter

Page 11: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu11

Reader

The value is returned as a Unicode.

java.io.Reader

+read(): int

+read(cbuf: char[]): int

+read(cbuf: char[], off: int, len: int): int

+close(): void

+skip(n: long): long

+markSupported(): boolean

+mark(readlimit: int): void

+reset(): void

Reads the next character from the input stream. The value returned is an int in the range from 0 to 65535, which represents a Unicode character. Returns -1 at the end of the stream.

Reads characters from the input stream into an array. Returns the actual number of characters read. Returns -1 at the end of the stream.

Reads characters from the input stream and stores into cbuf[off], cbuf[off+1], …, cbuf[off+len-1]. The actual number of bytes read is returned. Returns -1 at the end of the stream.

Closes this input stream and releases any system resources associated with the stream.

Skips over and discards n characters of data from this input stream. The actual number of characters 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.

Page 12: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu12

Writer

The Unicode value.

java.io.Writer

+write(int c): void

+write(cbuf: char[]): void

+write(cbuf: char[], off: int, len: int): void

+write(str: String): void

+write(str: String, off: int, len: int): void

+close(): void

+flush(): void

Writes the specified character to this output stream. The parameter c is the Unicode for a character.

Writes all the characters in array cbuf to the output stream.

Writes cbuf[off], cbuf[off+1], …, cbuf[off+len-1] into the output stream.

Writes the characters from the string into the output stream.

Writes a portion of the string characters into the output stream.

Closes this output stream and releases any system resources associated with the stream.

Flushes this output stream and forces any buffered output characters to be written out.

Page 13: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu13

FileReader/FileWriter

FileReader/FileWriter associates an input/output stream with an external file. All the methods in FileReader/FileWriter are inherited from its superclasses.

Reader

Writer

Object

PrintWriter

BufferedWriter

FileReader

FileWriter

InputStreamReader

BufferedReader

OutputStreamWriter

Page 14: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu14

FileReader

To construct a FileReader, use the following constructors:public FileReader(String filename)

public FileReader(File file)

A java.io.FileNotFoundException would occur if you attempt to create a FileReader with a nonexistent file.

TestFileReaderTestFileReader RunRun

Page 15: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu15

FileWriterTo construct a FileWriter, use the following constructors:

public FileWriter(String filename)public FileWriter(File file)public FileWriter(String filename, boolean append)public FileWriter(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.

TestFileWriterTestFileWriter RunRun

Page 16: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu16

InputStreamReader/OutputStreamWriterOptional

Reader

Writer

Object

PrintWriter

BufferedWriter

FileReader

FileWriter

InputStreamReader

BufferedReader

OutputStreamWriter

All the methods in InputStreamReader/OutputStreamWriter are inherited from Reader/Writer except getEncoding(), which returns the name of encoding being used by this stream.

Page 17: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu17

InputStreamReader/OutputStreamWriter

InputStreamReader/OutputStreamWriter are used to convert between bytes and characters. Characters written to an OutputStreamWriter are encoded into bytes using a specified encoding scheme. Bytes read from an InputStreamReader are decoded into characters using a specified encoding scheme. You can specify an encoding scheme using a constructor of InputStreamReader/OutputStreamWriter. If no encoding scheme is specified, the system’s default encoding scheme is used.

Optional

Program

The Unicode of the character is returned

A character is converted into the Unicode

The Unicode of the character is sent out

A character stored in a specified encoding

A character is converted into the code for the specified encoding

Page 18: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu18

BufferedReader/BufferedWriter

Reader

Writer

Object

PrintWriter

BufferedWriter

FileReader

FileWriter

InputStreamReader

BufferedReader

OutputStreamWriter

The buffered stream classes inherit methods from their superclasses. In addition to using the methods from their superclasses, BufferedReader has a readLine() method to read a line, and BufferedWriter has a newLine() method to write a line separator. If the end of stream is reached, readLine() returns null.

Page 19: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu19

PrintWriter/PrintStream

Reader

Writer

Object

PrintWriter

BufferedWriter

FileReader

FileWriter

InputStreamReader

BufferedReader

OutputStreamWriter

BufferedWriter is used to output characters and strings. PrintWriter and PrintStream can be used to output objects, strings and numeric values as text. PrintWriter was introduced in JDK 1.2 to replace PrintStream. Both classes are almost identical in the sense that they provide the same function and same methods for outputting strings and numeric values as text. PrintWriter is more efficient than PrintStream. So, you use PrintWriter rather than PrintStream.

Page 20: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu20

Methods in PrintWriter/PrintStream

public void print(Object o)

public void print(String s)

public void print(char c)

public void print(char[] cArray)

public void print(int i)

public void print(long l)

public void print(float f)

public void print(double d)

public void print(boolean b)

public void println(Object o)

public void println(String s)

public void println(char c)

public void println(char[] cArray)

public void println(int i)

public void println(long l)

public void println(float f)

public void println(double d)

public void println(boolean b)

PrintWriter and PrintStream also contain the JDK 1.5 printf method for printing formatted output, which was introduced in Section 2.17, “Formatted Output.”

Page 21: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu21

Constructing PrintWriter

This section introduces PrintWriter, but PrintStream can be used in the same way. To construct a PrintWriter, use the following constructors:

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

 If autoFlush is true, the println methods will cause the buffer to be flushed.

The constructors and methods in PrintWriter and PrintStream do not throw an IOException. So you don’t need to invoke them from a try-catch block.

TestPrintWriterTestPrintWriter RunRun

Page 22: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu22

Case Studies: Text Viewer

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.

FileViewerFileViewer RunRun

Page 23: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu23

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

The Unicode of the character

Encoding/ Decoding

The encoding of the character is stored in the file

Binary I/O

A byte is read/written

The same byte in the file

Binary I/O is more efficient

Page 24: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu24

Binary I/O Classes

InputStream

OutputStream

Object

ObjectOutputStream

FilterOutputStream

FileOutputStream

BufferedInputStream

DataInputStream

BufferedOutputStream

DataOutputStream

PrintStream

ObjectInputStream

FilterInputStream

FileInputStream

Page 25: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu25

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

Page 26: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu26

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.

Page 27: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu27

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

Page 28: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu28

FileInputStream

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.

Page 29: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu29

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

Page 30: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu30

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

Page 31: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu31

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.

Page 32: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu32

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)

Page 33: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu33

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( in: InputStream)

Page 34: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu34

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. writeBytes(String s) method writes the lower byte of the Unicode to the output.

Why UTF? What is UTF?UTF 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 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.

Page 35: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu35

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

Page 36: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu36

Checking End of File

TIP: If you keep reading data at the end of a stream, an EOFException would occur. 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 using writeUTF, you must read names using readUTF.

Page 37: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu37

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.

Page 38: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu38

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)

Page 39: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu39

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

Page 40: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu40

More on Text Files and Binary Files

Computers do not differentiate between a binary file and a text file. All files are stored in binary format. So, all files are essentially binary files.

Text I/O is built upon binary I/O to provide a level of abstraction for character encoding and decoding. Encoding and decoding are automatically performed by text I/O.

In general, you should use text input to read a file created by a text editor or a text output program, and use binary input to read a file created by a Java binary output program. For binary input, you need to know exactly how data were written in order to read them in correct type and order. Binary I/O also contains methods to read/write a character and string.

Page 41: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu41

Write a byte 199 as a numeric value

import java.io.*; public class Test { public static void main(String[] args) throws IOException { FileOutputStream output = new FileOutputStream("out.dat"); output.write(199); // Output byte 199 to the stream output.close();  FileInputStream input = new FileInputStream("out.dat"); System.out.println((char)input.read()); // Read and display a byte input.close(); }}

Binary stream out.dat

Output 199 0xC7 (199 in decimal) FileOutputStream

Character stream out.txt Output "199" 0x31 0x39 0x39

FileWriter

1 9 9

Here can’t be “199”, otherwise you use DataOutputStream

Demo Test.javaIf no “char”, then the numeric number will be printed

Page 42: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu42

Write a byte 199 as characters

import java.io.*;

 

public class Test {

public static void main(String[] args) throws IOException {

FileWriter output = new FileWriter("out.txt");

output.write("199"); // Output string "199" to the stream

output.close();

 

// Read and display three characters

FileReader input = new FileReader("out.txt");

System.out.print((char)input.read());

System.out.print((char)input.read());

System.out.println((char)input.read());

input.close();

}

}

Binary stream out.dat

Output 199 0xC7 (199 in decimal) FileOutputStream

Character stream out.txt Output "199" 0x31 0x39 0x39

FileWriter

1 9 9

Page 43: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu43

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

Page 44: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu44

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

You can replace DataInputStream/DataOutputStream completely with ObjectInputStream/ObjectOutputStream

Page 45: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu45

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

Page 46: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu46

Page 47: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu47

Using Object Streams

You 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

Page 48: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu48

Using Object Streams Sample

public class Student implements Serializable {

int id;

String name;

int age;

String department;

transient int number;

static int count;

}

Page 49: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu49

Using Object Streams Sample

public class Objectser {

public static void main(String args[]) {

Student stu=new Student(981036, “Li Ming”, 16, “CSD”);

try {

FileOutputStream fo = new FileOutputStream(“data.ser”);

ObjectOutputStream so = new ObjectOutputStream(fo);

so.writeObject(stu);

so.close();

}

catch(Exception e) {

System.err.println(e);

}

}

}

Page 50: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu50

Using Object Streams Samplepublic class ObjectRecov {

public static void main(String args[]) {

Student stu;

try {

FileInputStream fi = new FileInputStream(“data.ser”);

ObjectInputStream si = new ObjectInputStream(fi);

stu = (Student)si.readObject();

si.close();

System.out.println(“ID: ”+stu.id+“name:”+

stu.name+“age:”+age+“dept.:”+stu.department);

} catch(Exception e) {

System.out.println(e);

}

}

}

Can this statement put behind catch?

Page 51: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu51

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 Serializable.

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.

Page 52: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu52

The transient Keyword

The value of the objects’s static variables are not stored

If an object is an instance of Serializable, but it contains non-serializable instance data fields, the object can’t be serialized.

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.

Page 53: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu53

The transient Keyword, cont.

Consider the following class: public class Foo 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 Foo 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.

Page 54: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu54

Serializing Arrays

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 16.12 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.

TestObjectStreamForArrayTestObjectStreamForArray RunRun

Page 55: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu55

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.

Page 56: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu56

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

Page 57: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu57

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()

Page 58: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu58

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.

Page 59: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu59

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. seek(0) & seek(file.length());

long getFilePointer() IOException;

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

Page 60: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu60

RandomAccessFile Methods, cont.

long length()IOException

Returns the length of the file.

final void writeChar(int v) throws IOException

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

final void writeChars(String s)throws IOException

Writes a string to the file as a sequence ofcharacters.

Page 61: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu61

RandomAccessFile Constructor

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

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

Page 62: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu62

A Short Example on RandomAccessFile

RunRun

TestRandomAccessFileTestRandomAccessFile

Page 63: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu63

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.

Page 64: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu64

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

Page 65: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香

Liang,Introduction to Java Programming,revised by Dai-kaiyu65

Address Implementation

The rest of the work can be summarized in the following steps:

    Create the user interface.

Add a record to the file.

   Read a record from the file.

   Write the code to implement the button actions.

RunRun

AddressBookAddressBook