Bonjour,
j'ai besoin de faire un copier coller de fichier en java.
Pour cela, j'ai trouvé deux exemples de code qui répondent à mon besoin.
Voici le premier :
Et le deuxième :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 import java.io.*; public class JCopy{ public static void main(String args[]){ try { JCopy j = new JCopy(); j.copyFile(new File(args[0]),new File(args[1])); } catch (Exception e) { e.printStackTrace(); } } public void copyFile(File in, File out) throws Exception { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); byte[] buf = new byte[1024]; int i = 0; while((i=fis.read(buf))!=-1) { fos.write(buf, 0, i); } fis.close(); fos.close(); } }
Ma question est : comment déterminer le code le plus performant en ce qui concerne la vitesse ? Peut-on chronometrer le temps pour comparer les 2 bouts de code ?
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 import java.nio.channels.*; import java.io.*; public class JCopy2{ public static void main(String args[]){ try { JCopy2 j = new JCopy2(); j.copyFile(new File(args[0]),new File(args[1])); } catch (Exception e) { e.printStackTrace(); } } public void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); // or // destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); } }
Merci à vous
Partager