and this time right...
[mir.git] / source / mir / util / FileCopier.java
1 package mir.util;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7
8 public class FileCopier {
9   protected static final int FILE_COPY_BUFFER_SIZE = 65536;
10
11   protected FileCopier() {
12   }
13
14   public static void copyFile(File aSourceFile, File aDestinationFile) throws IOException {
15     FileInputStream inputStream;
16     FileOutputStream outputStream;
17     int nrBytesRead;
18     byte[] buffer = new byte[FILE_COPY_BUFFER_SIZE];
19
20     inputStream = new FileInputStream(aSourceFile);
21     try {
22       File directory = new File(aDestinationFile.getParent());
23         if (directory!=null && !directory.exists()){
24           directory.mkdirs();
25       }
26       outputStream = new FileOutputStream(aDestinationFile);
27       try {
28         do {
29           nrBytesRead = inputStream.read(buffer);
30           if (nrBytesRead>0)
31             outputStream.write(buffer, 0, nrBytesRead);
32         }
33         while (nrBytesRead>=0);
34       }
35       finally {
36         outputStream.close();
37       }
38     }
39     finally {
40       inputStream.close();
41     }
42   }
43
44   public static void copyDirectory(File aSourceDirectory, File aDestinationDirectory) throws IOException {
45     int i;
46     File sourceFile;
47     File destinationFile;
48     File[] files = aSourceDirectory.listFiles();
49
50     if (!aDestinationDirectory.exists())
51       aDestinationDirectory.mkdirs();
52
53     for (i=0; i<files.length; i++) {
54       sourceFile = files[i];
55       destinationFile=new File(aDestinationDirectory, sourceFile.getName());
56       if (sourceFile.isDirectory()) {
57         if (!destinationFile.exists())
58           destinationFile.mkdir();
59         copyDirectory(sourceFile, destinationFile);
60       }
61       else {
62         copyFile(sourceFile, destinationFile);
63       }
64     }
65   }
66
67   public static void copy(File aSource, File aDestination) throws IOException {
68     if (aSource.isDirectory()) {
69       copyDirectory(aSource, aDestination);
70     }
71     else if (aDestination.isDirectory()) {
72       copyFile(aSource, new File(aDestination, aSource.getName()));
73     }
74     else {
75       copyFile(aSource, aDestination);
76     }
77   }
78
79 }