venerdì 13 settembre 2013

Q1

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));

La risposta è C e E

A.
Anche se transferTo scrive sopra il file se è già esistente non cancella il file di partenza.
Quindi non realizza uno spostamento ma una copia.

B.
Il metodo copy senza opzioni non sovrascrive i file già esistenti e da luogo ad una java.nio.file.FileAlreadyExistsException.

C
Funziona bene perché con l’opzione il metodo copy sovrascrive il file di destinazione.

D
Il metodo move senza opzioni non sovrascrive i file già esistenti e da luogo ad una java.nio.file.FileAlreadyExistsException.

E
Funziona perché newBufferedWriter se il file esiste già lo tronca ad una dimensione pari a 0 prima di iniziare a scriverlo.

 
Riferimenti:

Nessun commento:

Posta un commento