KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgap > util > FileKit


1 /*
2  * This file is part of JGAP.
3  *
4  * JGAP offers a dual license model containing the LGPL as well as the MPL.
5  *
6  * For licencing information please see the file license.txt included with JGAP
7  * or have a look at the top of class org.jgap.Chromosome which representatively
8  * includes the JGAP license policy applicable for any file delivered with JGAP.
9  */

10 package org.jgap.util;
11
12 import java.io.*;
13 import java.util.jar.*;
14 import java.net.*;
15 import java.util.*;
16
17 public class FileKit {
18   /** String containing the CVS revision. Read out via reflection!*/
19   private final static String JavaDoc CVS_REVISION = "$Revision: 1.6 $";
20
21   public static String JavaDoc fileseparator = System.getProperty("file.separator");
22
23   /**
24    * Copies a complete file.
25    *
26    * @param source source file name
27    * @param dest destination file name or destination path (filename then taken
28    * from source)
29    * @throws FileNotFoundException
30    * @throws IOException
31    *
32    * @author Klaus Meffert
33    * @since 3.2
34    */

35   public static void copyFile(String JavaDoc source, String JavaDoc dest)
36       throws FileNotFoundException, IOException {
37     copyFile(source, dest, 0);
38   }
39
40   /**
41    * Copies a file.
42    *
43    * @param source source file name
44    * @param dest destination file name or destination path (filename then taken
45    * from source)
46    * @param a_offset start offset of file to copy (0 is begin of file)
47    * @throws FileNotFoundException
48    * @throws IOException
49    *
50    * @author Klaus Meffert
51    * @since 3.2
52    */

53   public static void copyFile(String JavaDoc source, String JavaDoc dest, int a_offset)
54       throws FileNotFoundException, IOException {
55     if (getFilename(dest).length() == 0) {
56       dest = dest + getFilename(source);
57     }
58     File inputFile = new File(source);
59     File outputFile = new File(dest);
60     FileInputStream in;
61     FileOutputStream out;
62     in = new FileInputStream(inputFile);
63     out = new FileOutputStream(outputFile);
64     int c;
65     int currentOffset = 0;
66     while ( (c = in.read()) != -1) {
67       if (currentOffset >= a_offset) {
68         out.write(c);
69       }
70       currentOffset++;
71     }
72     in.close();
73     out.close();
74   }
75
76   public static String JavaDoc getFilename(String JavaDoc name_and_path) {
77     return getFilename(name_and_path, fileseparator);
78   }
79
80   /**
81    * Extract file name from a given path+filename.
82    *
83    * @param name_and_path input
84    * @param fileseparator Slash or Backslash
85    * @return extracted file nmame
86    *
87    * @author Klaus Meffert
88    * @since 3.2
89    */

90   public static String JavaDoc getFilename(String JavaDoc name_and_path,
91                                    String JavaDoc fileseparator) {
92     /**@todo possibly use File.getName() instead? */
93     if (name_and_path == null) {
94       return "";
95     }
96     String JavaDoc s = name_and_path;
97 // s = common.strings.deQuote(s);
98
if (fileseparator.equals("/")) {
99       s = s.replace('\\', '/');
100     }
101     else {
102       s = s.replace('/', '\\');
103     }
104     int p = s.lastIndexOf(fileseparator);
105     if (p < 0) {
106       // No trailing file separator
107
return s;
108     }
109     else {
110       s = s.substring(p + 1);
111       if (s == null) {
112         s = "";
113       }
114       return s;
115     }
116   }
117
118   /**
119    * @return current directory of the application
120    * @throws IOException
121    *
122    * @author Klaus Meffert
123    * @since 3.2
124    */

125   public static String JavaDoc getCurrentDir()
126       throws IOException {
127     File file = new File(".");
128     return file.getCanonicalPath();
129   }
130
131   /**
132    * Adds a subdir to a given dir and returns the resulting dir.
133    *
134    * @param dir the original dir
135    * @param subDir the subdir to add
136    * @param makeNice true: call getNiceDir afterwards
137    * @return dir with subdir added
138    *
139    * @author Klaus Meffert
140    * @since 3.2
141    */

142   public static String JavaDoc addSubDir(String JavaDoc dir, String JavaDoc subDir, boolean makeNice) {
143     File f = new File(getConformPath(dir, true), subDir);
144     String JavaDoc s = getConformPath(f.getAbsolutePath(), makeNice);
145     return s;
146   }
147
148   public static String JavaDoc getConformPath(String JavaDoc path, boolean makeNice) {
149     if (makeNice) {
150       return getNiceURL(getConformPath(path), fileseparator);
151     }
152     else {
153       return getConformPath(path);
154     }
155   }
156
157   public static String JavaDoc getConformPath(String JavaDoc path) {
158     return getConformPath(path,fileseparator);
159   }
160
161   public static String JavaDoc getConformPath(String JavaDoc path, String JavaDoc a_fileseparator) {
162     String JavaDoc result = path;
163     if (a_fileseparator.equals("/")) {
164       result = removeDoubleSeparators(path.replace('\\', '/'));
165     }
166     else {
167       result = removeDoubleSeparators(path.replace('/', '\\'));
168     }
169     if (!result.endsWith(a_fileseparator)) {
170        result += a_fileseparator;
171     }
172     return result;
173   }
174
175   /**
176    * Makes an URL nice by bringing it into a normalized (i.e. convenient) form.
177    *
178    * @param url any URL
179    * @param separator the separator to remove duplicates of
180    * @return prettified URL
181    *
182    * @author Klaus Meffert
183    * @since 3.2
184    */

185   public static String JavaDoc getNiceURL(String JavaDoc url, String JavaDoc separator) {
186     if (url == null) {
187       return null;
188     }
189     if (url.length() == 0) {
190       return separator;
191     }
192     int p = url.lastIndexOf(separator);
193     if (p < url.length() - 1) {
194       return removeDoubleSeparators(url + separator);
195     }
196     else {
197       return removeDoubleSeparators(url);
198     }
199   }
200
201   /**
202    * Removes duplicate separators from an URL.
203    *
204    * @param dir name of directory including file name
205    * @return prettified URL
206    *
207    * @author Klaus Meffert
208    * @since 3.2
209    */

210   public static String JavaDoc removeDoubleSeparators(String JavaDoc dir) {
211     int p;
212     do {
213       String JavaDoc sep;
214       if (fileseparator.length() > 1) {
215         sep = fileseparator;
216       }
217       else {
218         sep = fileseparator + fileseparator;
219       }
220       p = dir.lastIndexOf(sep);
221       if (p >= 0) {
222         dir = dir.substring(0, p) + dir.substring(p + 1);
223       }
224       else {
225         break;
226       }
227     } while (true);
228     return dir;
229   }
230
231   public static boolean directoryExists(String JavaDoc a_dir) {
232     File f = new File(a_dir);
233     return f.exists();
234   }
235
236   public static boolean existsFile(String JavaDoc a_filename) {
237     File file = new File(getConformPath(a_filename));
238     return file.exists();
239   }
240
241   /**
242    * Deletes a file from disk.
243    *
244    * @param a_filename name of file to delete
245    * @return true if deletion successful
246    */

247   public static boolean deleteFile(String JavaDoc a_filename) {
248     File file = new File(getConformPath(a_filename));
249     if (file.exists()) {
250       return file.delete();
251     }
252     else {
253       return false;
254     }
255   }
256
257   /**
258    * Loads a jar file and returns a class loader to access the jar's classes.
259    *
260    * @param a_filename the full jar file name, e.g.:
261    * C:/jgap/lib/ext/ashcroft.jar
262    * @return ClassLoader the class loader with which to access the loaded
263    * classes, e.g. by <classloader>.loadClass(<classname including package>),
264    * e.g.: cl.loadClass("com.thoughtworks.ashcroft.runtime.JohnAshcroft");
265    * @throws Exception
266    *
267    * @author Klaus Meffert
268    * @since 3.2
269    */

270   public static ClassLoader JavaDoc loadJar(String JavaDoc a_filename)
271       throws Exception JavaDoc {
272 // URL url = new URL("jar:file:" + a_filename);
273
JarClassLoader cl = new JarClassLoader(a_filename);
274     return cl;
275   }
276
277   /**
278    * Retrieve the manifest included in the given jar.
279    *
280    * @param a_filename jar file name
281    * @return Manifest included in the given jar
282    * @throws Exception
283    *
284    * @author Klaus Meffert
285    * @since 3.2
286    */

287   public static Manifest getManifestOfJar(String JavaDoc a_filename)
288       throws Exception JavaDoc {
289     URL url = new URL("jar:file:" + a_filename + "!/");
290     JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
291     Manifest manifest = jarConnection.getManifest();
292     // Very important: Close the jar file!
293
// -----------------------------------
294
jarConnection.getJarFile().close();
295     return manifest;
296   }
297
298   /**
299    * @param a_JGAPManifest Manifest with JGAP-specific information
300    * @return version the jar file is working wit (or version of the JGAP library
301    * in case the file *is* the JGAP library)
302    *
303    * @author Klaus Meffert
304    * @since 3.2
305    */

306   public static String JavaDoc getJGAPVersion(Manifest a_JGAPManifest) {
307     Attributes attr = a_JGAPManifest.getMainAttributes();
308     return attr.getValue("JGAP-Version");
309   }
310
311   /**
312    * @param a_JGAPManifest Manifest with JGAP-specific information
313    * @return version of the module represented by the jar
314    *
315    * @author Klaus Meffert
316    * @since 3.2
317    */

318   public static String JavaDoc getModuleVersion(Manifest a_JGAPManifest) {
319     Attributes attr = a_JGAPManifest.getMainAttributes();
320     return attr.getValue("Module-Version");
321   }
322
323   /**
324    * See getModuleVersion.
325    *
326    * @param a_filename name of a JGAP jar
327    * @return version of the module represented by the jar
328    * @throws Exception
329    *
330    * @author Klaus Meffert
331    * @since 3.2
332    */

333   public static String JavaDoc getVersionOfModule(String JavaDoc a_filename)
334       throws Exception JavaDoc {
335     Manifest mf = getManifestOfJar(a_filename);
336     String JavaDoc version = getModuleVersion(mf);
337     if (version == null) {
338       version = "no version info found!";
339     }
340     return version;
341   }
342
343   /**
344    * See getJGAPVersion.
345    *
346    * @param a_filename name of a JGAP jar
347    * @return version the jar file is working wit (or version of the JGAP library
348    * in case the file *is* the JGAP library)
349    * @throws Exception
350    *
351    * @author Klaus Meffert
352    * @since 3.2
353    */

354   public static String JavaDoc getVersionOfJGAP(String JavaDoc a_filename)
355       throws Exception JavaDoc {
356     Manifest mf = getManifestOfJar(a_filename);
357     String JavaDoc version = getJGAPVersion(mf);
358     if (version == null) {
359       version = "no version info found!";
360     }
361     return version;
362   }
363
364   /**
365    * Converts an ordinary file name into a jar filename that can be used with
366    * JarClassLoader.
367    *
368    * @param a_filename the name to convert
369    * @return converted name
370    *
371    * @author Klaus Meffert
372    * @since 3.2
373    */

374   public static String JavaDoc toJarFileName(String JavaDoc a_filename) {
375     String JavaDoc result = a_filename.replace('\\', '/');
376 // if (!result.endsWith("!/")) {
377
// result += "!/";
378
// }
379
return result;
380   }
381
382   /**
383    * Creates a directory, and if necessary, any of its parent directories.
384    *
385    * @param a_dirname name of the dir to create
386    * @throws IOException
387    *
388    * @author Klaus Meffert
389    * @since 3.2
390    */

391   public static void createDirectory(String JavaDoc a_dirname)
392       throws IOException {
393     File file = new File(a_dirname);
394     if (file.exists()) {
395       return;
396     }
397     if (!file.mkdirs()) {
398       throw new IOException("Directory " + a_dirname +
399                             " could not be created!");
400     }
401   }
402
403   /**
404    * Reads a text file.
405    *
406    * @param a_filename name of text file
407    * @return list of read text lines
408    * @throws IOException
409    *
410    * @author Klaus Meffert
411    * @since 3.2
412    */

413   public static Vector readFile(String JavaDoc a_filename)
414       throws IOException {
415
416       Vector v = new Vector();
417       String JavaDoc thisLine;
418       FileInputStream fin = new FileInputStream(a_filename);
419       BufferedReader myInput = new BufferedReader
420           (new InputStreamReader(fin));
421       while ( (thisLine = myInput.readLine()) != null) {
422         v.add(thisLine);
423       }
424       return (v);
425   }
426
427 }
428
Popular Tags