-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileExample.java
More file actions
61 lines (54 loc) · 1.87 KB
/
Copy pathFileExample.java
File metadata and controls
61 lines (54 loc) · 1.87 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
55
56
57
58
59
60
61
package Java7;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class FileExample {
public static void main(String[] args) {
//Approach 1:
System.out.println(
"File Copy using FileReader, BufferedReader and FileWriter");
fileCopy();
//Approach 2:
System.out.println("File Copy using Files.copy()");
fileCopy2();
}
//File Copy Approach 1
static void fileCopy() {
String sourceFile = "C:\\fullpath\\files\\input.txt";
String targetFile = "C:\\fullpath\\output.txt";
try (FileReader fr = new FileReader(sourceFile);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(targetFile)) {
while (true) {
String line = br.readLine();
if (line == null) {break;}
fw.write(line + "\n");
}
System.out.println("File Copied Successfully");
} catch (FileNotFoundException fe) {
System.out.println("File not found: " + fe.getMessage());
} catch (IOException io) {
System.out.println(
"Error Occurred During writing to file." + io.getMessage());
} catch (Exception e) {
System.out.println("Other Exception occurred. " + e.getMessage());
}
}
//File Copy Approach 2
static void fileCopy2() {
Path source = Paths.get("C:\\PATH\\files", "input.txt");
Path target = Paths.get("C:\\PATH\\files", "target2.txt");
try {
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
System.out.println("File Copied Successfully");
} catch (IOException io) {
System.out.println("Error Occurred: " + io.getMessage());
}
}
}