Java Reference
In-Depth Information
and
FileOutputStream
to high-level streams to buffer and fi lter the data into appropriate data
types.
The following
CopyFile
program demonstrates these two classes by reading the bytes
from one fi le and copying them into another, making a byte-by-byte copy of the fi le:
1. package com.sybex.io;
2.
3. import java.io.*;
4.
5. public class CopyFile {
6. public static void copy(File src, File dest)
7. throws IOException {
8. FileInputStream in = new FileInputStream(src);
9. FileOutputStream out = new FileOutputStream(dest);
10. int c;
11. try {
12. while((c = in.read()) != -1) {
13. out.write(c);
14. }
15. }finally{
16. in.close();
17. out.close();
18. }
19. }
20.
21. public static void main(String [] args) {
22. try {
23. File source = new File(“States.class”);
24. File destination = new File(“copyofStates.class”);
25. copy(source, destination);
26. }catch(IOException e) {
27. e.printStackTrace();
28. }
29. }
30. }
The following breakdown illustrates what the
CopyFile
program does:
1.
Within
main
on lines 23 and 24, two
File
objects are instantiated to represent the
pathnames to the source and destination files.
2.
The
copy
method is called on line 25, and the two
File
references are copied into the
src
and
dest
parameters.
Search WWH ::
Custom Search