Repository navigation
Expand file tree
/
Copy pathCopy.java
More file actions
54 lines (46 loc) · 1.41 KB
/
Copy pathCopy.java
File metadata and controls
54 lines (46 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.io.*;
public class Copy {
/** Main method
@param args[0] for sourcefile
@param args[1] for target file
*/
public static void main(String[] args) throws IOException {
// Check command-line parameter usage
if (args.length != 2) {
System.out.println(
"Usage: java Copy sourceFile targetfile");
System.exit(1);
}
// Check if source file exists
File sourceFile = new File(args[0]);
if (!sourceFile.exists()) {
System.out.println("Source file " + args[0]
+ " does not exist");
System.exit(2);
}
// Check if target file exists
File targetFile = new File(args[1]);
if (targetFile.exists()) {
System.out.println("Target file " + args[1]
+ " already exists");
System.exit(3);
}
// Create an input stream
BufferedInputStream input =
new BufferedInputStream(new FileInputStream(sourceFile));
// Create an output stream
BufferedOutputStream output =
new BufferedOutputStream(new FileOutputStream(targetFile));
// Continuously read a byte from input and write it to output
int r, numberOfBytesCopied = 0;
while ((r = input.read()) != -1) {
output.write((byte)r);
numberOfBytesCopied++;
}
// Close streams
input.close();
output.close();
// Display the file size
System.out.println(numberOfBytesCopied + " bytes copied");
}
}