KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > columba > core > io > DiskIO


1 //The contents of this file are subject to the Mozilla Public License Version 1.1
2
//(the "License"); you may not use this file except in compliance with the
3
//License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
4
//
5
//Software distributed under the License is distributed on an "AS IS" basis,
6
//WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
7
//for the specific language governing rights and
8
//limitations under the License.
9
//
10
//The Original Code is "The Columba Project"
11
//
12
//The Initial Developers of the Original Code are Frederik Dietz and Timo Stich.
13
//Portions created by Frederik Dietz and Timo Stich are Copyright (C) 2003.
14
//
15
//All Rights Reserved.
16

17 package org.columba.core.io;
18
19 import java.io.BufferedOutputStream JavaDoc;
20 import java.io.BufferedReader JavaDoc;
21 import java.io.BufferedWriter JavaDoc;
22 import java.io.File JavaDoc;
23 import java.io.FileInputStream JavaDoc;
24 import java.io.FileOutputStream JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.InputStream JavaDoc;
27 import java.io.InputStreamReader JavaDoc;
28 import java.io.OutputStreamWriter JavaDoc;
29 import java.net.URL JavaDoc;
30 import java.util.logging.Logger JavaDoc;
31
32 /**
33  * Utility methods for handling files and directories.
34  */

35 public final class DiskIO {
36
37     private static final Logger JavaDoc LOG = Logger.getLogger("org.columba.core.io");
38
39     private static String JavaDoc resourceFolder = "";
40
41     /**
42      * Private constructor for utility class.
43      */

44     private DiskIO() {
45         // don't instantiate this
46
}
47
48     /**
49      * Ensures the existence of the directory specified by the parameter. If the
50      * directory does not exist, an attempt is performed to create it including
51      * all necessary parent directories that may be implied by the
52      * specification. ### HELPME : against what should a relative pathname be
53      * made absolute? ### ### We need to set the installation directory
54      * somewhere! ####
55      *
56      * @param dir
57      * File specifying the intended directory name; if the specified
58      * name is a relative path, it is always made absolute against
59      * the program's <b>installationDirectory </b>.
60      * @return <b>true </b> if and only if the specified file exists and is a
61      * directory
62      */

63     public static boolean ensureDirectory(File JavaDoc dir) {
64         if (dir == null) {
65             throw new IllegalArgumentException JavaDoc("dir = null");
66         }
67         boolean success = true;
68         if (!dir.isDirectory()) {
69             success = !dir.isFile() && dir.mkdirs();
70
71             if (success) {
72                 LOG.info("Created directory: " + dir.toString());
73             } else {
74                 LOG.severe("failed while trying to create directory: "
75                         + dir.toString());
76             }
77         }
78
79         return success;
80     }
81
82     // ensureDirectory
83
public static boolean ensureDirectory(String JavaDoc path) {
84         return ensureDirectory(new File JavaDoc(path));
85     }
86
87     public static void saveStringInFile(File JavaDoc toFile, String JavaDoc insertString)
88             throws IOException JavaDoc {
89         BufferedWriter JavaDoc out;
90
91         out = new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(new FileOutputStream JavaDoc(
92                 toFile), "ISO-8859-1"));
93         out.write(insertString);
94         out.flush();
95         out.close();
96     }
97
98     public static void saveStreamInFile(File JavaDoc toFile, InputStream JavaDoc is)
99             throws IOException JavaDoc {
100
101         BufferedOutputStream JavaDoc out = new BufferedOutputStream JavaDoc(
102                 new FileOutputStream JavaDoc(toFile));
103
104         StreamUtils.streamCopy(is, out);
105
106         out.flush();
107         out.close();
108
109         is.close();
110     }
111
112     // saveStringInFile
113
public static String JavaDoc readFileInString(File JavaDoc fromFile) throws IOException JavaDoc {
114         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc((int) fromFile.length());
115
116         BufferedReader JavaDoc in = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(
117                 new FileInputStream JavaDoc(fromFile), "ISO-8859-1"));
118         String JavaDoc str;
119         strbuf = new StringBuffer JavaDoc((int) fromFile.length());
120
121         while ((str = in.readLine()) != null) {
122             strbuf.append(str + "\n");
123         }
124
125         in.close();
126
127         return strbuf.toString();
128
129         /*
130          * int lineNumber = 0; byte[] buffer = new byte[1024]; int read;
131          * StringBuffer out = new StringBuffer((int)fromFile.length());
132          * FileInputStream in = new FileInputStream( fromFile );
133          *
134          * read = in.read(buffer); while ( read == 1024 ) { out.append(new
135          * String(buffer,"ISO-8859-1")); read = in.read(buffer); }
136          *
137          * out.append(new String(buffer,0,read,"ISO-8859-1")); in.close();
138          *
139          * return out.toString();
140          */

141     }
142
143     // saveStringInFile
144

145     /**
146      * Deletes the directory specified by the parameter and all of its contents.
147      * This does recurse into subdirectories. Function reports errors. If the
148      * parameter does not denote a directory, <b>false </b> is always returned.
149      *
150      * @param dir
151      * a File representing the directory to be delete
152      * @return <b>true </b> if and only if the directory does not exist on
153      * termination; a return value <b>false </b> does not imply that
154      * there were no files deleted
155      * @throws IllegalArgumentException
156      * if the parameter is <b>null </b>
157      */

158     public static boolean deleteDirectory(File JavaDoc dir) {
159         File JavaDoc[] files;
160         File JavaDoc f;
161         int i;
162         boolean success = true;
163
164         if (dir == null) {
165             throw new IllegalArgumentException JavaDoc("dir = null");
166         }
167
168         if (!dir.isDirectory()) {
169             return false;
170         }
171
172         files = dir.listFiles();
173
174         for (i = 0; i < files.length; i++) {
175             if ((f = files[i]).isDirectory()) {
176                 deleteDirectory(f);
177             } else if (!f.delete()) {
178                 LOG.severe("*** failed to delete file " + f.getAbsolutePath());
179             }
180         }
181
182         success = dir.delete();
183
184         if (!success) {
185             LOG.severe("*** failed to delete directory "
186                     + dir.getAbsolutePath());
187         }
188
189         return success;
190     }
191
192     // deleteDirectory
193

194     /**
195      * Deletes the contents of an existing directory. (May be applied to
196      * non-existing files without causing error.)
197      *
198      * @return <b>true </b> if and only if on termination the directory exists
199      * and is empty
200      */

201     public static boolean emptyDirectory(File JavaDoc dir) {
202         boolean success;
203
204         if (dir == null) {
205             throw new IllegalArgumentException JavaDoc("dir = null");
206         }
207
208         if ((success = dir.exists() && deleteDirectory(dir))) {
209             dir.mkdirs();
210         }
211
212         return success && dir.exists();
213     }
214
215     // emptyDirectory
216

217     /**
218      * General use columba resource InputStream getter.
219      *
220      * @param path
221      * the full path and filename of the resource requested. If
222      * <code>path</code> begins with "#" it is resolved against the
223      * program's standard resource folder after removing "#"
224      * @return an InputStream to read the resource data, or <b>null </b> if the
225      * resource could not be obtained
226      * @throws java.io.IOException
227      * if there was an error opening the input stream
228      */

229     public static InputStream JavaDoc getResourceStream(String JavaDoc path)
230             throws java.io.IOException JavaDoc {
231         URL JavaDoc url;
232
233         if ((url = getResourceURL(path)) == null) {
234             return null;
235         }
236         return url.openStream();
237     }
238
239     // getResourceStream
240

241     /**
242      * General use columba resource URL getter.
243      *
244      * @param path
245      * the full path and filename of the resource requested. If
246      * <code>path</code> begins with "#" it is resolved against the
247      * program's standard resource folder after removing "#"
248      * @return an URL instance, or <b>null </b> if the resource could not be
249      * obtained
250      * @throws java.io.IOException
251      * if there was an error opening the input stream
252      */

253     public static URL JavaDoc getResourceURL(String JavaDoc path) // throws
254
// java.io.IOException
255
{
256         URL JavaDoc url;
257
258         if (path == null) {
259             throw new IllegalArgumentException JavaDoc("path = null");
260         }
261
262         if (path.startsWith("#")) {
263             path = resourceFolder + path.substring(1);
264         }
265
266         // url = ClassLoader.getSystemResource(path);
267
url = DiskIO.class.getResource("/" + path);
268
269         if (url == null) {
270             LOG.info("*** failed locating resource: " + path);
271
272             return null;
273         }
274
275         return url;
276     }
277
278     // getResourceURL
279
public static void setResourceRoot(String JavaDoc path) {
280         if (path == null) {
281             resourceFolder = "";
282         } else {
283             if (!path.endsWith("/")) {
284                 path += "/";
285             }
286
287             resourceFolder = path;
288         }
289     }
290
291     // setResourceRoot
292
public static String JavaDoc getResourceRoot() {
293         return resourceFolder;
294     }
295
296     /**
297      * Copies the contents of any disk file to the specified output file. The
298      * output file will be overridden if it exist. Function reports errors.
299      *
300      * @param inputFile
301      * a File object
302      * @param outputFile
303      * a File object
304      * @throws java.io.IOException
305      * if the function could not be completed because of an IO error
306      */

307     public static void copyFile(File JavaDoc inputFile, File JavaDoc outputFile)
308             throws java.io.IOException JavaDoc {
309         FileInputStream JavaDoc in;
310         FileOutputStream JavaDoc out;
311
312         byte[] buffer = new byte[512];
313         int len;
314
315         try {
316             out = new FileOutputStream JavaDoc(outputFile);
317             in = new FileInputStream JavaDoc(inputFile);
318
319             while ((len = in.read(buffer)) != -1) {
320                 out.write(buffer, 0, len);
321             }
322
323             in.close();
324             out.close();
325         } catch (IOException JavaDoc e) {
326             LOG.info("*** error during file copy "
327                     + outputFile.getAbsolutePath() + ": " + e.getMessage());
328             throw e;
329         }
330     }
331
332     // copyFile
333

334     /**
335      * Copies a system resource to the specified output file. The output file
336      * will be overridden if it exist, so the calling routine has to take care
337      * about unwanted deletions of content. Function reports errors.
338      *
339      * @param resource
340      * a full resource path. If the value begins with "#", it is
341      * resolved against the program's standard resource folder after
342      * removing "#"
343      * @return <b>true </b> if and only if the operation was successful,
344      * <b>false </b> if the resource was not found
345      * @throws java.io.IOException
346      * if there was an IO error
347      */

348     public static boolean copyResource(String JavaDoc resource, File JavaDoc outputFile)
349             throws java.io.IOException JavaDoc {
350         InputStream JavaDoc in;
351         FileOutputStream JavaDoc out;
352         byte[] buffer = new byte[512];
353         int len;
354
355         // attempt
356
try {
357             if ((in = DiskIO.getResourceStream(resource)) == null) {
358                 return false;
359             }
360
361             out = new FileOutputStream JavaDoc(outputFile);
362
363             while ((len = in.read(buffer)) != -1) {
364                 out.write(buffer, 0, len);
365             }
366
367             out.close();
368             in.close();
369
370             LOG.fine("created : " + outputFile.getAbsolutePath());
371         } catch (IOException JavaDoc e) {
372             LOG.severe("*** error during resource file copy "
373                     + outputFile.getAbsolutePath() + ": " + e.getMessage());
374             throw e;
375         }
376
377         return true;
378     }
379
380     // copyResource
381
public static String JavaDoc readStringFromResource(String JavaDoc resource)
382             throws java.io.IOException JavaDoc {
383         InputStream JavaDoc in;
384
385         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
386
387         // attempt
388
try {
389             if ((in = DiskIO.getResourceStream(resource)) == null) {
390                 return "";
391             }
392
393             BufferedReader JavaDoc reader = new BufferedReader JavaDoc(
394                     new InputStreamReader JavaDoc(in));
395
396             String JavaDoc nextLine = reader.readLine();
397
398             while (nextLine != null) {
399                 result.append(nextLine);
400                 result.append("\n");
401                 nextLine = reader.readLine();
402             }
403
404             in.close();
405         } catch (IOException JavaDoc e) {
406             e.printStackTrace();
407             throw e;
408         }
409
410         return result.toString();
411     }
412
413     /**
414      * Results equal
415      * <code>copyResource ( String resource, new File (outputFile) )</code>.
416      */

417     public static boolean copyResource(String JavaDoc resource, String JavaDoc outputFile)
418             throws java.io.IOException JavaDoc {
419         return copyResource(resource, new File JavaDoc(outputFile));
420     }
421 }
Popular Tags