Given the code fragment:
public static void main(String[] args) {
String source =”d:\\company\\info.txt”;
String dest =”d:\\company\\emp\\info.txt”;
// insert code fragment here. Line ***
} catch (IOException e) {
System.err.println(“Caught IOException”+ e.getMessage());
}
}
Which two try statements, when inserted at line ***, enable the code to successfully move the file info.txt to the destination directory, even if a file by the same name already exists in the destination directory?
A.
try (FileChannel in = new FileInputStream (source). getChannel(); FileChannel out = new FileOutputStream(dest).getChannel()) { in.transferTo(0, in.size(), out);
B.
try (Files.copy(Paths.get(source),Paths.get(dest));
Files.delete (Paths.get(source));
C.
try (Files.copy(Paths.get(source), Paths.get(dest),StandardCopyOption.REPLACE_Existing); Files.delete(Paths.get(source));
D.
try (Files.move(Paths.get(source),Paths.get(dest));
E.
try(BufferedReader br = Files.newBufferedReader(Paths.get(source), Charset.forName(“UTF- 8”));
BufferedWriter bw = Files.newBufferedWriter(Paths.get(dest), Charset.forName(“UTF-8”)); String record = “”;
while ((record = br.readLine()) ! = null) {
bw.write(record);
bw.newLine();
}
Files.delete(Paths.get(source));
Explanation:
C: Copies and overwrites the destination file (thanks toStandardCopyOption.REPLACE_Existing).
Deletes the original file.
E: By default the buffered writer replaces the existing file.This is what is needed in this scenario.
C must be like following:
try {
Files.copy(Paths.get(source), Paths.get(dest), StandardCopyOption.REPLACE_EXISTING);
Files.delete(Paths.get(source));
B & D both miss CopyOption
A misses delete()
It don’t have the richtig ansver.
A – misses delete();
B,C,D,E – kann work, but have syntax error
C, E
A, C are the right answer!!!!
Indeed, C and E is correct. Perer is right!
A is not right because it does not delete the source file.
A: copies only, don’t move operation
B,C,D (no try-with-resource !) syntax change to: try { …
B: throws FileAlreadyExistsException
C: correct if syntax change to : StandardCopyOption.REPLACE_EXISTING
D: throws FileAlreadyExistsException
E: works properly if the sourcefile has the correct format, utf-8 here (else throws MalformedInputException) AND syntax is corrected to:
try ( BufferedReader br = Files.newBufferedReader(Paths.get(source), Charset.forName(“UTF-8”));
BufferedWriter bw = Files.newBufferedWriter(Paths.get(dest), Charset.forName(“UTF-8”)); ){
String record = “”;
…..
+1
a