Io18 File Handeling
-
Upload
deepak-chaudhary -
Category
Documents
-
view
359 -
download
0
Transcript of Io18 File Handeling
-
7/28/2019 Io18 File Handeling
1/64
Input and Output
Text and Binary I/OChapter 19
Introduction to Java Y.Daniel Liang 1
-
7/28/2019 Io18 File Handeling
2/64
File Input and Output
Programs to run are in the FileIO folder:
1. ScannerDriver.java
2. ScannerFile.javaScannerTextfile.txt (input file)
ScannerOutputfile.txt (output file)
3. Inventory.java (Driver)
InventoryItem.java
input file: inventory.txtIntroduction to Java Y.Daniel Liang 2
-
7/28/2019 Io18 File Handeling
3/64
File Input and Output
Programs to run contd.
4. TestPrint.java
5. TestPrintWriter.java Team #1
output file: pw.txt
6. TestFileStream Team #2
7. TestDataStream Team #3
output file: temp.datIntroduction to Java Y.Daniel Liang 3
-
7/28/2019 Io18 File Handeling
4/64
File Input and Output
Programs to run contd.
8. Copy.java Team #4
Welcome.java (source file)Temp. java (target file)
9. TestObjectStreamForArray Team #5
Introduction to Java Y.Daniel Liang 4
-
7/28/2019 Io18 File Handeling
5/64
Objectives
To understand how I/O is processed in Java
To distinguish between text I/O and binary
I/O
To read data from the console using the
Scanner class
To read data from a file using the Scanner
class Introduction to Java Y.Daniel Liang 5
-
7/28/2019 Io18 File Handeling
6/64
Objectives contd.
To write data to a file using the PrintWriterclass
To read and write bytes using FileInputStream and FileOutputStream
To read and write primitive values andstrings using DataInputStream/
DataOutPutStream
Introduction to Java Y.Daniel Liang 6
-
7/28/2019 Io18 File Handeling
7/64
Objectives contd.
To store and restore objects usingObjectOutputStream 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
To know how to serialize arrays
Introduction to Java Y.Daniel Liang 7
-
7/28/2019 Io18 File Handeling
8/64
Input and Output
Introduction
Data held in variables, arrays, and objects aretemporary. Data are lost when the program
ceases processing
To save the data created during the life of the
program, you must save the data in a file onto a
disk, CD, or some other storage device .
Then the file can be transported and can be
read later by other programs
Introduction to Java Y.Daniel Liang 8
-
7/28/2019 Io18 File Handeling
9/64
ntro uct onRedirection of Input and Output
It is tedious to test programs by typing data in for every test run.
Testing is far easier if the program reads input from a file.
You can prepare the file once and reuse it for many tests.
The command line interfaces of most operating systems provide a way
to link a file to the input of a program, as if all the characters in the
file had actually been typed by the user .
Introduction to Java Y.Daniel Liang 9
t t
-
7/28/2019 Io18 File Handeling
10/64
ntro uct onRedirection of Input and Output example:
java ClassName < data.txt > output.txt
Use input redirection to avoid repetitive typing during testing.
Use output redirection to save your program output in a file.
Introduction to Java Y.Daniel Liang 10
-
7/28/2019 Io18 File Handeling
11/64
Introduction contd.
Data are stored in two basic formats:
text and binary
Text file is represented in human-readable form
Examples oftext files that you can read:
Files that are created with a simple text exitor ,
such as Windows Vista NotePad, as well as Java
source code, and HTML Files
Introduction to Java Y.Daniel Liang 11
-
7/28/2019 Io18 File Handeling
12/64
Introduction contd.
Data stored in a binary file are represented in binary
form. You cannot read binary files. The files are
designed to be read by programs.
Binary files consists of a series of bits
Text file consist of a series of characters.
Introduction to Java Y.Daniel Liang 12
-
7/28/2019 Io18 File Handeling
13/64
Introduction contd.
The advantages of binary files are that:
1. They are more efficient to process than text
files. Text I/O requires encoding and decodingwhereas binary I/O does not.
2. Binary files are independent of the encoding
scheme on the host machine and thus are
portable.
Introduction to Java Y.Daniel Liang 13
-
7/28/2019 Io18 File Handeling
14/64
Introduction to Java Y.Daniel Liang
The Scanner class
The simplest tool for reading text files is theScanner class.
Class java.util.Scanner
14
-
7/28/2019 Io18 File Handeling
15/64
Introduction to Java Y.Daniel Liang
to Get Input from the Console Using the Scanner Class
Run ScannerDriverprogram in the FileIO Folder
next(): reading a string. A string delimeter is a space
nextByte(): reading an integer of the byte type
nextShort(): reading an integer of the short type
nextInt(): reading an integer of the int type
nextLong(): reading an integer of the long type
nextFloat(): reading a number of the float type
nextDouble(): reading number of the double type
15
-
7/28/2019 Io18 File Handeling
16/64
Introduction to Java Y.Daniel Liang
To Get Input from a text file Using the Scanner Class
Run ScannerFileProgram in the FileIO Folder
The action of reading data from a
file is called file input.
16
f f
-
7/28/2019 Io18 File Handeling
17/64
Introduction to Java Y.Daniel Liang
To read text data from a disk file, we use the FileReaderand
BufferedReaderobjects.
We first construct a FileReader object
with the name of the file Then we associate a BufferedReaderobject to the file.
Then we read data, using the readLine method of the
BufferedReader class.
Finally, we convert the String to a primitive data type as
necessary.
Run Programs: InventoryItem (Driver)Inventory
Use input file: inventory.txt
17
-
7/28/2019 Io18 File Handeling
18/64
Introduction to Java Y.Daniel Liang
Sample code for processing a text file:
String file = customer.txt;
String line;try{
FileReader fr = new FileReader (file);
BufferedReader inFile = new BufferedReader(fr);
line = inFile.readLine();
while(line != null && count < MAX) {tokenizer = new StringTokenizer(line);
name = tokenizer.nextToken();
18
C td
-
7/28/2019 Io18 File Handeling
19/64
Introduction to Java Y.Daniel Liang
Contd.
try{
custNumber = Long.parseLong (tokenizer.
nextToken());balance = Double.parseDouble(tokenizer.
nextToken());
phone = tokenizer.nextToken();
custsArray[count++] = new Customer(name,
custNumber, balance, phone);
} // end inner try block
catch (NumberFormatException e) { }
line = inFile.readLine();
}// end while block
inFile.close();
19
-
7/28/2019 Io18 File Handeling
20/64
Introduction to Java Y.Daniel Liang
PrintWriter is an object we use to generate an output text
file.
PrintWriter supports only two output methods:
print
println (for print line)
Run program TestPrinterWriter
output file: pw.txt
20
-
7/28/2019 Io18 File Handeling
21/64
Introduction to Java Y.Daniel Liang
Constructors of the
PrintWriter
PrintWriter(Writer out)
PrintWriter(Writer out, booleanautoFlush)
PrintWriter(OutputStream out)
PrintWriter(OutputStream out, boolean
autoFlush)
21
-
7/28/2019 Io18 File Handeling
22/64
PrintWriter Methods
Introduction to Java Y.Daniel Liang
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)
22
St
-
7/28/2019 Io18 File Handeling
23/64
StreamsIn Java, all I/O is handled in streams.
Astream is an abstraction of the continuous one-way flow of data. The programreceives data thru the input stream and sends data thru the output stream.
Any source of input or destination for output is called a stream.
Program
Output Stream
File
Input Stream
Introduction to Java Y.Daniel Liang 23Introduction to Java Y.Daniel Liang
-
7/28/2019 Io18 File Handeling
24/64
Introduction to Java Y.Daniel Liang 24
Streams
All streams except random-access filestreams flow in only one direction;therefore if you want to input and output,you need two separate stream objects.
Streams are objects. Stream objects havemethods that read and write data , flush the
stream, close the stream, and count thenumber of bytes in the stream, etc.
Bi I/O
-
7/28/2019 Io18 File Handeling
25/64
Introduction to Java Y.Daniel Liang 2525
Binary I/O
Text 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 acharacter.
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 characterEncoding/
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
-
7/28/2019 Io18 File Handeling
26/64
Introduction to Java Y.Daniel Liang 26
Binary I/O Classes
The design of the Java I/O classes is a good example ofapplying inheritance, where common methods are generalized
in superclasses, and sub classes provide specialized methods.
See next slide. It list some of the classes for performingbinary I/O.
InputStream is the root for binary input classes.
OutputStream is the root for binary output classes
-
7/28/2019 Io18 File Handeling
27/64
27Introduction to Java Y.Daniel Liang 27
Binary I/O Classes
InputStream
OutputStream
Object
ObjectOutputStream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
-
7/28/2019 Io18 File Handeling
28/64
Stream Classes
The stream classes can be categorized into two types: bytestreams and character streams.
The InputStream/OutputStream class is theroot of all byte stream classes,
the Reader/Writer class is the root of all characterstream.
The subclasses ofInputStream/OutputStream are analogous to thesubclasses ofReader/Writer.
Introduction to Java Y.Daniel Liang 28
To Read and Write Binar Data from /To a Disk File
-
7/28/2019 Io18 File Handeling
29/64
Introduction to Java Y.Daniel Liang
To Read and Write Binary Data from /To a Disk File
FileInputStream and FileOutputStream- all methods in these
classes are inherited from InputStream and OutputStream
(java.io. FileInputStream and java.io.FileOutputStream )
Create a FileInputStream:
FileInputStream inputStream = new
FileInputStream inputStream (
input.bin);
To write Binary Data to a Disk File:
FileOutputStream outputStream = new
FileOutputStream outputStream (
output.bin);
29
I tSt
-
7/28/2019 Io18 File Handeling
30/64
Introduction to Java Y.Daniel Liang 30
InputStream
java.io.InputStream
int read(byte[] b) throws IOException
abstract int read() throws IOException
void close() throws IOException
int available() throws IOException
long skip(long n) throws IOException
Note: The abstract InputStream class defines
the methods for the input stream of bytes
O t tSt
-
7/28/2019 Io18 File Handeling
31/64
Introduction to Java Y.Daniel Liang 31
OutputStream
java.io.OutputStream
abstract void write(int b) throws
IOException
void write(byte[] b) throws IOException
void close() throws IOException
void flush() throws IOException
Note: The abstract OutputStream class
defines the methods for the output
stream of bytes.
-
7/28/2019 Io18 File Handeling
32/64
Introduction to Java Y.Daniel Liang 32
FileInputStream/FileOutputStream
FileInputStream/FileOutputStream associates abinary input/output stream with an external file.
All the methods inFileInputStream/FileOuptputStream are inheritedfrom its superclasses.
InputStream
OutputStream
Object
ObjectOutputStream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
-
7/28/2019 Io18 File Handeling
33/64
Introduction to Java Y.Daniel Liang 33
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.
-
7/28/2019 Io18 File Handeling
34/64
Introduction to Java Y.Daniel Liang 34
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 alreadyexists, the first two constructors would delete the current contents inthe file. To retain the current content and append new data into the
file, use the last two constructors by passing true to the appendparameter.
-
7/28/2019 Io18 File Handeling
35/64
Introduction to Java Y.Daniel Liang 35
FileOutputStream
The program TestFileStream uses binary I/O towrite ten bytes values from 1 to 10 to a filenamed temp.dat
TestFileStream Run
http://localhost/var/www/apps/conversion/tmp/scratch_5/html/TestFileStream.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_5/html/TestFileStream.html -
7/28/2019 Io18 File Handeling
36/64
Introduction to Java Y.Daniel Liang 36
FilterInputStream/FilterOutputStream
Filter streams are streams that filter bytes for some purpose. The basic byte input stream providesa 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 inputstream. Using a filter class enables you to read integers, doubles, and strings instead of bytes andcharacters. 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
-
7/28/2019 Io18 File Handeling
37/64
Introduction to Java Y.Daniel Liang 37
DataInputStream/DataOutputStreamDataInputStream reads bytes from the streamand 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.
-
7/28/2019 Io18 File Handeling
38/64
Introduction to Java Y.Daniel Liang 38
DataInputStream
DataInputStream extends FilterInputStreamand 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)
-
7/28/2019 Io18 File Handeling
39/64
Introduction to Java Y.Daniel Liang 39
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 ofevery character in the string s.
OutputStream
FilterOutputStream
DataOutputStream
+DataOutputStream(
out: OutputStream)
-
7/28/2019 Io18 File Handeling
40/64
Introduction to Java Y.Daniel Liang 40
Characters and Strings in Binary I/O
A Unicode consists of two bytes. ThewriteChar(char c) method writes the Unicode ofcharacter c to the output.
The writeChars(String s) method writes theUnicode for each character in the string s to the
output.
-
7/28/2019 Io18 File Handeling
41/64
Introduction to Java Y.Daniel Liang 4141
Characters and Strings in Binary I/OWhy UTF-8? What is UTF-8?
UTF-8 (8-bit UCS/Unicode Transformation Format) is a codingscheme that allows systems to operate with both ASCII and Unicodeefficiently. Most operating systems use ASCII.
Java uses Unicode. The ASCII character set is a subset of theUnicode character set. Since most applications need only the ASCIIcharacter set, it is a waste to represent an 8-bit ASCII character as a
16-bit Unicode character.
-
7/28/2019 Io18 File Handeling
42/64
Introduction to Java Y.Daniel Liang 4242
Characters and Strings in Binary I/OWhy UTF-8? What is UTF-8?
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. OtherUnicode values are coded in three bytes.
-
7/28/2019 Io18 File Handeling
43/64
Introduction to Java Y.Daniel Liang
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 thefollowing constructors:
public DataInputStream(InputStream instream)
public DataOutputStream(OutputStream outstream)
The statements given below create data streams. The first statementcreates an input stream for file in.dat; the second statement creates anoutput stream for file out.dat.
DataInputStream infile =
new DataInputStream(new FileInputStream("in.dat"));
DataOutputStream outfile =
new DataOutputStream(new FileOutputStream("out.dat"));
-
7/28/2019 Io18 File Handeling
44/64
Introduction to Java Y.Daniel Liang
Using DataInputStream/DataOutputStream
DataInputStream and DataOutputStream read and write data primitive
types values and strings in a machine-independent fashion.
Thereby enabling you to write a data file on one machine and read iton another machine that has a different operating system or file
structure.
An application uses a data output stream to write data that can later beread by a program using a data input stream.
-
7/28/2019 Io18 File Handeling
45/64
Introduction to Java Y.Daniel Liang
Using DataInputStream/DataOutputStream
The TestDataStream program writes student names and
scores to a file named temp.dat and reads the data back fromthe file.
TestDataStream Run
Order and Format
http://localhost/var/www/apps/conversion/tmp/scratch_5/html/TestDataStream.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_5/html/TestDataStream.html -
7/28/2019 Io18 File Handeling
46/64
Introduction to Java Y.Daniel Liang 46
Checking End of File
TIP: If you keep reading data at the end of a stream, an EOFExceptionwould occur. So how do you check the end of a file? You can useinput.available() to check it. input.available() == 0 indicates that it isthe end of a file.
Order and Format
See program TestDataStream
CAUTION: You have to read the data in the same order and sameformat in which they are stored. For example, since names are writtenin UTF-8 using writeUTF, you must read names using readUTF.
-
7/28/2019 Io18 File Handeling
47/64
Introduction to Java Y.Daniel Liang 4747
BufferedInputStream/BufferedOutputStream
Reduces the number of reads and writes
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.
-
7/28/2019 Io18 File Handeling
48/64
Introduction to Java Y.Daniel Liang 48
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)
i
-
7/28/2019 Io18 File Handeling
49/64
Introduction to Java Y.Daniel Liang 49
Constructing
BufferedInputStream/BufferedOutputStream
Improve the performance of the TestDataStream program byadding buffers in the streams in lines 6-7 and 21-22, as follows:
DataOutputStream output = new DataOutputStream(
new BufferedOutputStream(new
FileOutputStream(temp.dat));
DataInputStream input = new DataInputStream(
new BufferedInputStream(newFileInputStream(temp.dat));
C S di C il
-
7/28/2019 Io18 File Handeling
50/64
Introduction to Java Y.Daniel Liang 5050
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 argumentsusing the following command:
java Copy source target
The program copies a source file to a target file and displays thenumber of bytes in the file. If the source does not exist, tell the userthe file is not found. If the target file already exists, tell the user thefile already exists.
C S di C Fil
-
7/28/2019 Io18 File Handeling
51/64
Introduction to Java Y.Daniel Liang 5151
Case Studies: Copy File
The program uses the File class to check whether the source file
and the target file exist.
The program copies a Java source file to an identical Java file
Copy Run
bj /
Optional
http://localhost/var/www/apps/conversion/tmp/scratch_5/html/Copy.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_5/html/Copy.html -
7/28/2019 Io18 File Handeling
52/64
Introduction to Java Y.Daniel Liang 52
Object I/O
DataInputStream/DataOutputStream enables you to perform I/O for
objects in addition to primitive type values and strings.ObjectInputStream/ObjectOutputStream enables you to perform I/Ofor objects in addition for primitive type values and strings.
InputStream
OutputStream
Object
ObjectOutputStream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
p
Obj S
-
7/28/2019 Io18 File Handeling
53/64
Introduction to Java Y.Daniel Liang 53
ObjectInputStream
ObjectInputStream extends InputStream andimplements ObjectInput and ObjectStreamConstants.
java.io.ObjectInput
+readObject(): Object Reads an object.
java.io.InputStream
java.io.ObjectInputStream
+ObjectInputStream(in: InputStream)
java.io.DataInput
ObjectStreamConstants
Obj O S
-
7/28/2019 Io18 File Handeling
54/64
Introduction to Java Y.Daniel Liang 54
ObjectOutputStream
ObjectOutputStream extends OutputStream andimplements ObjectOutput and ObjectStreamConstants.
java.io.ObjectOutput
+writeObject(o: Object): void Writes an object.
ava.io.OutputStream
java.io.ObjectOutputStream
+ObjectOutputStream(out: OutputStream)
java.io.DataOutput
ObjectStreamConstants
U i Obj S
-
7/28/2019 Io18 File Handeling
55/64
Introduction to Java Y.Daniel Liang 55
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)
TestObjectOutputStream Run
TestObjectInputStream Run
Object Streams
http://localhost/var/www/apps/conversion/tmp/scratch_5/html/TestObjectOutputStream.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_5/html/TestObjectInputStream.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_5/html/TestObjectInputStream.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_5/html/TestObjectOutputStream.html -
7/28/2019 Io18 File Handeling
56/64
Introduction to Java Y.Daniel Liang 56
Object StreamsThe ObjectInputStream class can save entire object out to a
disk, and the C class can read them back in.
Objects are saved in binary format; therefore, you use streams
and not writers.
For example, you can write a Bank Account object to a file:
BankAccount bk = new ;
ObjectOutputStream out = new ObjectOutputStream (
new FileOutputStream(bank.dat));
Out.writeObject(bk);
Object Streams
-
7/28/2019 Io18 File Handeling
57/64
Introduction to Java Y.Daniel Liang 57
Object StreamsUse Object streams to save and restore all instance fields of an
object automatically.
When reading the object back in, you use the readObject
method of the ObjectInputStream class. That method returns
an Object reference, so you need to remember the types of the
objects that you saved and use a cast:
ObjectInputStream in = new ObjectInputStream (
new FileInputStream(bank.dat));
BankAccount bk = (BankAccount) in.readObject( );
The readObject method can throw a ClassNotFoundException-
it is a checked exception, so you need to catch or declare it.
The Serializable Interface
-
7/28/2019 Io18 File Handeling
58/64
Introduction to Java Y.Daniel Liang 58
The Serializable InterfaceNot all objects can be written to an output stream. Objects that can be
written to an object stream is said to beserializable. A serializable
object is an instance of the java.io.Serializable interface. So the classof 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 implementsSerializable.
public MyClass implements Serializable{
// Definition of the class
}
Implementing this interface enables the Java serialization mechanism
to automate the process of storing the objects and arrays.
Th t i t K d
-
7/28/2019 Io18 File Handeling
59/64
Introduction to Java Y.Daniel Liang 59
The transient Keyword
If an object is an instance of Serializable, but it containsnon-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 JVMto ignore these fields when writing the object to an object
stream.
Th t i t K d t
-
7/28/2019 Io18 File Handeling
60/64
Introduction to Java Y.Daniel Liang 60
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 werenot marked transient, a java.io.NotSerializableException would occur.
S i li i A
-
7/28/2019 Io18 File Handeling
61/64
Introduction to Java Y.Daniel Liang 61
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. Note : java.io.File implements
Comparable and Serializable
TestObjectStreamForArray Run
More about the Serializable Interface
Th f i bj i ll d i li i b
http://localhost/var/www/apps/conversion/tmp/scratch_5/html/TestObjectStreamForArray.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_5/html/TestObjectStreamForArray.html -
7/28/2019 Io18 File Handeling
62/64
Introduction to Java Y.Daniel Liang 62
The process of saving objects to a stream is called serialization because
each object is assigned a serial number on the stream. If the same object
is saved twice, only the serial number is written out the second time.
When the objects are read back in, duplicate serial numbers are restored
as reference to the same object.
Why dont all classes implementSerializable
?
For security reasons, some programmers may not want to serialize
classes with confidential contents. Once a class is serializable, anyone
can write its objects to disk and analyze the disk file.
There are also some classes that contain values that are meaningless oncea program exists, such as operatingsystem-specific font descriptors.
These values should not be serialized.
R d A Fil
-
7/28/2019 Io18 File Handeling
63/64
Introduction to Java Y.Daniel Liang 63
Random Access Files
All of the streams you have used so far are known as
read-only orwrite-only streams.
The external files of these streams aresequentialfiles that
cannot be updated without creating a new file.
It is often necessary to modify files or to insert newrecords into files.
Java provides the RandomAccessFile class to allow a fileto be read from and writen to at random locations.
R d A Fil
-
7/28/2019 Io18 File Handeling
64/64
RandomAccessFile
Creates a RandomAccessFile stream with the specified File object andmode.
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, startingat the current file pointer.
Writes len bytes from the specified byte array starting at offset off to
thi fil
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):