Java Reference
In-Depth Information
3.
Line 8 instantiates a
FileInputStream
for
src
and line 9 instantiates a
FileOutput-
Stream
for
dest
.
4.
The
while
loop on line 12 reads one byte at time from the source file. If the
read
method returns
-1
, the end of the file has been reached and the
while
loop terminates.
Otherwise, the byte is written to the destination file.
5.
Be sure to close all streams, as done on lines 16 and 17.
Notice that the source fi le I chose to copy was a bytecode fi le, which is not just character
data. (The
Reader
and
Writer
classes would not have worked for this application because
the data is raw bytes.) An exact copy of
States.class
is created in a new fi le named
copyofStates.class
.
The next section discusses two useful high-level streams,
DataInputStream
and
DataOutputStream
, which fi lter byte streams into primitive types and strings.
The
DataInputStream
and
DataOutputStream
Classes
The
CopyFile
program from the previous section used only low-level streams, but most
input and output use the high-level streams as well. For example, the
DataInputStream
and
DataOutputStream
classes are high-level streams that contain methods for reading and writ-
ing the eight Java primitive types as well as
String
objects. The following
ContactManager
program demonstrates the
DataInputStream
and
DataOutputStream
classes. The program
uses the following
Contact
class, a basic representation of a person's contact information:
1. package com.sybex.io;
2.
3. public class Contact {
4. public String name;
5. public int age;
6. public long cellPhone;
7.
8. public Contact(String name, int age, long cellPhone) {
9. this.name = name;
10. this.age = age;
11. this.cellPhone = cellPhone;
12. }
13.
14. public String toString() {
15. return name + “ “ + age + ” “ + cellPhone + ”\n”;
16. }
17. }
Search WWH ::
Custom Search