The following code is to copy the file from the source to destination and replace if already exists.
Code:-
import java.nio.file.*;
import java.util.*;
import java.nio.file.CopyOption.*;
public class Copy {
String spth, tpth;
Path source, target;
Scanner scan = new Scanner(System.in);
public void input() {
try {
System.out.printf("SOURCE: ");
spth = scan.nextLine();
System.out.printf("TARGET: ");
tpth = scan.nextLine();
} catch (InputMismatchException e) {
System.err.println("Error Occur!\n" + e.getMessage());
System.exit(0);
}
}
public void copy() {
try {
source = Paths.get(spth);
target = Paths.get(tpth);
Files.copy(source, target.resolve(source.getFileName()));
spth = spth.substring(spth.lastIndexOf("\\"), spth.length());
tpth = tpth.concat(spth);
target = Paths.get(tpth);
if (Files.exists(target)) {
System.out.println("RESULT: COPIED!");
} else {
System.out.println("RESULT: FAILED TO COPY!");
}
} catch (Exception e) {
System.err.println("Error Occur!\n" + e.getMessage());
System.exit(0);
}
}
public void copyFileContents() {
try {
CopyOption[] REPLACE_EXISTING;
REPLACE_EXISTING = new CopyOption[]{StandardCopyOption.ATOMIC_MOVE};
Files.copy(source, target, REPLACE_EXISTING);
} catch (Exception e) {
System.err.println("Error Occur!\n" + e.getMessage());
System.exit(0);
}
}
public static void main(String[] args) {
Copy cp = new Copy();
cp.input();
cp.copy();
}
}
Code:-
import java.nio.file.*;
import java.util.*;
import java.nio.file.CopyOption.*;
public class Copy {
String spth, tpth;
Path source, target;
Scanner scan = new Scanner(System.in);
public void input() {
try {
System.out.printf("SOURCE: ");
spth = scan.nextLine();
System.out.printf("TARGET: ");
tpth = scan.nextLine();
} catch (InputMismatchException e) {
System.err.println("Error Occur!\n" + e.getMessage());
System.exit(0);
}
}
public void copy() {
try {
source = Paths.get(spth);
target = Paths.get(tpth);
Files.copy(source, target.resolve(source.getFileName()));
spth = spth.substring(spth.lastIndexOf("\\"), spth.length());
tpth = tpth.concat(spth);
target = Paths.get(tpth);
if (Files.exists(target)) {
System.out.println("RESULT: COPIED!");
} else {
System.out.println("RESULT: FAILED TO COPY!");
}
} catch (Exception e) {
System.err.println("Error Occur!\n" + e.getMessage());
System.exit(0);
}
}
public void copyFileContents() {
try {
CopyOption[] REPLACE_EXISTING;
REPLACE_EXISTING = new CopyOption[]{StandardCopyOption.ATOMIC_MOVE};
Files.copy(source, target, REPLACE_EXISTING);
} catch (Exception e) {
System.err.println("Error Occur!\n" + e.getMessage());
System.exit(0);
}
}
public static void main(String[] args) {
Copy cp = new Copy();
cp.input();
cp.copy();
}
}
Comments