here

advertisement
CIS 270—App Dev II
Big Java Chapter 19
Files and Streams
19.1 Text and Binary Formats I
• Data can be stored in text format
characters
– Text is a human-readable sequence of ____________
– The integer 12,345 is stored as the following sequence
of Unicode characters: ‘1’ ‘2’ ‘3’ ‘4’ ‘5’
– Text I/O is easy for humans
Writer
– Reader and _________
classes (and their subclasses)
used for text input/output
– To read text data from a file in Java,
FileReader reader = new FileReader(“input.txt”);
– To write text data to a file in Java,
FileWriter writer = new FileWriter(“output.txt”);
read() reads characters
– The Reader method _______
19.1 Text and Binary Formats II
• Data can also be stored in binary format
bytes
– Binary is a machine-readable sequence of ________
– The integer 12,345 is stored as the following sequence
of 4 bytes: 00000000 00000000 00011000 00111001
– Binary I/O is more efficient for digital computers
OutputStream classes (and their
– InputStream and ____________
subclasses) are used for binary input/output
– To read binary data from a file in Java,
FileInputStream inputStream = new FileInputStream
(“input.bin”);
– To write text data to a file in Java,
FileOutputStream outputStream = new FileOutputStream
(“output.txt”);
read() reads bytes
– The InputStream method _______
19.2 An Encryption Program
• The CaesarEncryptor class gets the input and
output file names, and the key, from the user,
streams for the files, creates
creates input/output _______
a CaesarCipher object, which then calls its
encryptStream() method.
• The CaesarCipher class reads a character from an
key and writes
input file, applies an encryption _____,
the encrypted character to an output file.
–
–
–
–
int next = in.read();
byte b = (byte) next;
byte c = (byte) (b + key);
out.write(c);
19.3 Random (Direct) Access
• It is more efficient to directly access a specific data
record in a file than to sequentially read/write all
records.
• To know where to go in a file, all data fields must
fixed size large enough to hold each item.
be of ______
Binary format is better for records of fixed size.
• ________
• Code examples:
– (int) file.length()/RECORD_SIZE // number of records
– file.seek(n * RECORD_SIZE) // move to nth record
– file.readInt() // read the next int in that record
19.4 Object Streams
• A program can write data fields separately or can
objects at once (binary format).
write entire ________
– BankAccount b = new BankAccount();
– ObjectOutputStream out = new ObjectOutputStream( new
FileOutputStream( “bank.dat” );
– out.writeObject( b );
• Reading objects is similar.
– ObjectInputStream in = new ObjectInputStream( new
FileInputStream( “bank.dat” );
– BankAccount b = (BankAccount) in.readObject();
• Another technique is to store several objects in an
array and then store that array and save it.
• If objects use streams, the class must implement the
Serializable interface (objects have serial
_____ numbers).
Download