KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > localhistory > utils > FileUtils


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.localhistory.utils;
21
22 import java.io.*;
23 import org.openide.ErrorManager;
24 import org.openide.filesystems.FileUtil;
25
26 /**
27  * // XXX clean up
28  * @author pkuzel
29  */

30 public class FileUtils {
31
32     /**
33      * Copies the specified sourceFile to the specified targetFile.
34      */

35     public static void copyFile(File sourceFile, File targetFile) throws IOException {
36         if (sourceFile == null || targetFile == null) {
37             throw new NullPointerException JavaDoc("sourceFile and targetFile must not be null"); // NOI18N
38
}
39
40         InputStream inputStream = null;
41         try {
42             inputStream = createInputStream(sourceFile);
43             copy(inputStream, targetFile);
44         } finally {
45             if (inputStream != null) {
46                 try {
47                     inputStream.close();
48                 }
49                 catch (IOException ex) {
50                     // ignore
51
}
52             }
53         }
54     }
55
56     public static void copy(File file, OutputStream os) throws IOException {
57         if (file == null ) {
58             throw new NullPointerException JavaDoc("file must not be null"); // NOI18N
59
}
60         if (os == null ) {
61             throw new NullPointerException JavaDoc("output stream must not be null"); // NOI18N
62
}
63         InputStream is = null;
64         try {
65             is = createInputStream(file);
66             FileUtil.copy(is, os);
67         } finally {
68             if (is != null) { try { is.close(); } catch (IOException ex) { } }
69             if (os != null) { try { os.close(); } catch (IOException ex) { } }
70         }
71     }
72     
73     public static void copyDirFiles(File sourceDir, File targetDir) {
74         copyDirFiles(sourceDir, targetDir, false);
75     }
76     
77     public static void copyDirFiles(File sourceDir, File targetDir, boolean preserveTimestamp) {
78         File[] files = sourceDir.listFiles();
79
80         if(files==null || files.length == 0) {
81             targetDir.mkdirs();
82             if(preserveTimestamp) targetDir.setLastModified(sourceDir.lastModified());
83             return;
84         }
85         if(preserveTimestamp) targetDir.setLastModified(sourceDir.lastModified());
86         for (int i = 0; i < files.length; i++) {
87             try {
88                 File target = FileUtil.normalizeFile(new File(targetDir.getAbsolutePath() + "/" + files[i].getName())); // NOI18N
89
if(files[i].isDirectory()) {
90                     copyDirFiles(files[i], target, preserveTimestamp);
91                 } else {
92                     FileUtils.copyFile (files[i], target);
93                     if(preserveTimestamp) target.setLastModified(files[i].lastModified());
94                 }
95             } catch (IOException ex) {
96                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex); // should not happen
97
}
98         }
99     }
100     
101     /**
102      * Copies the specified sourceFile to the specified targetFile.
103      * It <b>closes</b> the input stream.
104      */

105     public static void copy(InputStream inputStream, File targetFile) throws IOException {
106         if (inputStream == null || targetFile == null) {
107             throw new NullPointerException JavaDoc("sourcStream and targetFile must not be null"); // NOI18N
108
}
109
110         // ensure existing parent directories
111
File directory = targetFile.getParentFile();
112         if (!directory.exists() && !directory.mkdirs()) {
113             throw new IOException("Could not create directory '" + directory + "'"); // NOI18N
114
}
115
116         OutputStream outputStream = null;
117         try {
118             outputStream = createOutputStream(targetFile);
119             try {
120                 byte[] buffer = new byte[32768];
121                 for (int readBytes = inputStream.read(buffer);
122                      readBytes > 0;
123                      readBytes = inputStream.read(buffer)) {
124                     outputStream.write(buffer, 0, readBytes);
125                 }
126             }
127             catch (IOException ex) {
128                 targetFile.delete();
129                 throw ex;
130             }
131         }
132         finally {
133             if (inputStream != null) {
134                 try {
135                     inputStream.close();
136                 }
137                 catch (IOException ex) {
138                     // ignore
139
}
140             }
141             if (outputStream != null) {
142                 try {
143                     outputStream.close();
144                 }
145                 catch (IOException ex) {
146                     // ignore
147
}
148             }
149         }
150     }
151
152     /**
153      * Recursively deletes all files and directories under a given file/directory.
154      *
155      * @param file file/directory to delete
156      */

157     public static void deleteRecursively(File file) {
158         if (file.isDirectory()) {
159             File [] files = file.listFiles();
160             for (int i = 0; i < files.length; i++) {
161                 deleteRecursively(files[i]);
162             }
163         }
164         file.delete();
165     }
166     
167     /**
168      * Do the best to rename the file.
169      * @param orig regular file
170      * @param dest regular file (if exists it's rewritten)
171      */

172     public static void renameFile(File orig, File dest) throws IOException {
173         boolean destExists = dest.exists();
174         if (destExists) {
175             for (int i = 0; i<3; i++) {
176                 if (dest.delete()) {
177                     destExists = false;
178                     break;
179                 }
180                 try {
181                     Thread.sleep(71);
182                 } catch (InterruptedException JavaDoc e) {
183                 }
184             }
185         }
186
187         if (destExists == false) {
188             for (int i = 0; i<3; i++) {
189                 if (orig.renameTo(dest)) {
190                     return;
191                 }
192                 try {
193                     Thread.sleep(71);
194                 } catch (InterruptedException JavaDoc e) {
195                 }
196             }
197         }
198
199         // requires less permisions than renameTo
200
FileUtils.copyFile(orig, dest);
201
202         for (int i = 0; i<3; i++) {
203             if (orig.delete()) {
204                 return;
205             }
206             try {
207                 Thread.sleep(71);
208             } catch (InterruptedException JavaDoc e) {
209             }
210         }
211         throw new IOException("Can not delete: " + orig.getAbsolutePath()); // NOI18N
212
}
213
214     /**
215      * This utility class needs not to be instantiated anywhere.
216      */

217     private FileUtils() {
218     }
219     
220     public static BufferedInputStream createInputStream(File file) throws IOException {
221         int retry = 0;
222         while (true) {
223             try {
224                 return new BufferedInputStream(new FileInputStream(file));
225             } catch (IOException ex) {
226                 retry++;
227                 if (retry > 7) {
228                     throw ex;
229                 }
230                 try {
231                     Thread.sleep(retry * 34);
232                 } catch (InterruptedException JavaDoc iex) {
233                     throw ex;
234                 }
235             }
236         }
237     }
238     
239     public static BufferedOutputStream createOutputStream(File file) throws IOException {
240         int retry = 0;
241         while (true) {
242             try {
243                 return new BufferedOutputStream(new FileOutputStream(file));
244             } catch (IOException ex) {
245                 retry++;
246                 if (retry > 7) {
247                     throw ex;
248                 }
249                 try {
250                     Thread.sleep(retry * 34);
251                 } catch (InterruptedException JavaDoc iex) {
252                     throw ex;
253                 }
254             }
255         }
256     }
257
258     /** Creates new tmp dir in java.io.tmpdir */
259     public static File createTmpFolder(String JavaDoc prefix) {
260         String JavaDoc tmpDir = System.getProperty("java.io.tmpdir"); // NOI18N
261
File tmpFolder = new File(tmpDir);
262         File checkoutFolder = null;
263         try {
264             // generate unique name for tmp folder
265
File tmp = File.createTempFile(prefix, "", tmpFolder); // NOI18N
266
if (tmp.delete() == false) {
267                 return checkoutFolder;
268             }
269             if (tmp.mkdirs() == false) {
270                 return checkoutFolder;
271             }
272             checkoutFolder = FileUtil.normalizeFile(tmp);
273         } catch (IOException e) {
274             ErrorManager err = ErrorManager.getDefault();
275             err.notify(e);
276         }
277         return checkoutFolder;
278     }
279
280     
281 }
282
Popular Tags