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