KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > snow > utils > storage > FileUtils


1 package snow.utils.storage;
2
3 import java.text.DecimalFormat JavaDoc;
4
5 import java.io.*;
6 import java.util.*;
7 import java.util.zip.*;
8
9 /** all file access should be done from here
10 */

11 public final class FileUtils
12 {
13
14   private FileUtils()
15   {
16   } // Constructor
17

18   public static Class JavaDoc getLockForFileAccess()
19   {
20     return FileUtils.class;
21   }
22
23   public static Vector<Object JavaDoc> loadVectorFromFile(File file) throws Exception JavaDoc
24   {
25     synchronized( FileUtils.getLockForFileAccess() )
26     {
27       if(!file.exists()) throw new Exception JavaDoc("File "+file.getAbsolutePath()+" doesn't exist");
28       FileInputStream fis = null;
29       DataInputStream dis = null;
30       Vector<Object JavaDoc> v = new Vector<Object JavaDoc>();
31       try
32       {
33          fis = new FileInputStream(file);
34          dis = new DataInputStream(fis);
35          VectorUtils.streamToVector(dis, v);
36          dis.close();
37          return v;
38       }
39       catch(Exception JavaDoc e)
40       {
41         throw e;
42       }
43       finally
44       {
45         if(fis!=null) fis.close();
46       }
47     }
48   }
49
50   public static List<Object JavaDoc> loadZippedVectorFromFile(File file) throws Exception JavaDoc
51   {
52     synchronized( FileUtils.getLockForFileAccess() )
53     {
54       if(!file.exists()) throw new Exception JavaDoc(
55         "File "+file.getAbsolutePath()+" doesn't exist");
56       FileInputStream fis = null;
57       GZIPInputStream zis = null;
58       DataInputStream dis = null;
59       try
60       {
61          fis = new FileInputStream(file);
62          zis = new GZIPInputStream(fis);
63          dis = new DataInputStream(zis);
64          List<Object JavaDoc> v = VectorUtils.receiveVector(dis);
65          dis.close();
66          return v;
67       }
68       catch(Exception JavaDoc e)
69       {
70         throw e;
71       }
72       finally
73       {
74         if(fis!=null) fis.close();
75       }
76     }
77   }
78
79   /** load the vector from the inputstream.
80     Caution: the stream is not closed, this allow you to read several vectory from the stream
81     a header and a body, for example.
82   */

83   public static Vector<Object JavaDoc> loadVector(InputStream is) throws Exception JavaDoc
84   {
85     synchronized( FileUtils.getLockForFileAccess() )
86     {
87       DataInputStream dis = null;
88       Vector<Object JavaDoc> v = new Vector<Object JavaDoc>();
89       try
90       {
91          dis = new DataInputStream(is);
92          VectorUtils.streamToVector(dis, v);
93          dis.close();
94          return v;
95       }
96       catch(Exception JavaDoc e)
97       {
98         throw e;
99       }
100     }
101   }
102
103   public static void saveVectorToFile(File file, Vector<Object JavaDoc> v) throws Exception JavaDoc
104   {
105     synchronized( FileUtils.getLockForFileAccess() )
106     {
107       if(file.exists())
108       {
109         // delete
110
if(!file.delete())
111         {
112            throw new Exception JavaDoc(
113              "File "+file.getAbsolutePath()+" already exists and cannot be deleted"
114                );
115         }
116       }
117       FileOutputStream fos = null;
118       DataOutputStream dos = null;
119       try
120       {
121          fos = new FileOutputStream(file);
122          dos = new DataOutputStream(fos);
123          VectorUtils.vectorToStream(dos, v);
124       }
125       catch(Exception JavaDoc e)
126       {
127         throw e;
128       }
129       finally
130       {
131         if(fos!=null) fos.close();
132       }
133     }
134   }
135
136   public static void addToZip(ZipOutputStream zos, File f, String JavaDoc relName) throws Exception JavaDoc
137   {
138     synchronized( FileUtils.getLockForFileAccess() )
139     {
140       FileInputStream fis = null;
141       try
142       {
143         ZipEntry ze = new ZipEntry(relName);
144         ze.setTime(f.lastModified());
145         zos.putNextEntry(ze);
146         fis = new FileInputStream(f);
147         byte[] buffer = new byte[256];
148         int read = 0;
149         while((read=fis.read(buffer))!=-1)
150         {
151           zos.write(buffer,0,read);
152         }
153         zos.closeEntry();
154       }
155       catch(Exception JavaDoc e)
156       {
157         throw e;
158       }
159       finally
160       {
161         if(fis!=null) fis.close();
162       }
163     }
164   }
165
166
167
168   public static byte[] getFileContent(File file) throws Exception JavaDoc
169   {
170    synchronized( FileUtils.getLockForFileAccess() )
171    {
172     ByteArrayOutputStream baos = new ByteArrayOutputStream();
173     FileInputStream fis = null;
174     try
175     {
176       fis = new FileInputStream(file);
177       byte[] buf = new byte[256];
178       int read = -1;
179       while((read=fis.read(buf))!=-1)
180       {
181          baos.write(buf,0,read);
182       }
183       baos.flush();
184       baos.close();
185       return baos.toByteArray();
186     }
187     catch(Exception JavaDoc e)
188     {
189       throw e;
190     }
191     finally
192     {
193      if(fis!=null) fis.close();
194     }
195    }
196   }
197
198   public static String JavaDoc getStringContent(InputStream ins) throws Exception JavaDoc
199   {
200    synchronized( FileUtils.getLockForFileAccess() )
201    {
202     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
203     InputStreamReader is = null;
204     try
205     {
206       is = new InputStreamReader(ins);
207       char[] buf = new char[256];
208       int read = -1;
209       while((read=is.read(buf))!=-1)
210       {
211          sb.append(new String JavaDoc(buf,0,read));
212       }
213       return sb.toString();
214     }
215     catch(Exception JavaDoc e)
216     {
217       throw e;
218     }
219     finally
220     {
221      if(is!=null) is.close();
222     }
223    }
224   }
225
226
227   public static void saveToFile(byte[] cont, File file) throws Exception JavaDoc
228   {
229    synchronized( FileUtils.getLockForFileAccess() )
230    {
231     FileOutputStream fos = null;
232     try
233     {
234       fos = new FileOutputStream(file);
235       fos.write(cont);
236     }
237     catch(Exception JavaDoc e)
238     {
239       throw e;
240     }
241     finally
242     {
243      if(fos!=null) fos.close();
244     }
245    }
246   }
247
248 /** @param is is closed in all situations.
249 */

250  public static void writeToFile(InputStream is, File file) throws Exception JavaDoc
251  {
252     File parent = file.getParentFile();
253     if(parent!=null && !parent.exists())
254     {
255        parent.mkdirs();
256     }
257
258     FileOutputStream fos = null;
259     try
260     {
261       fos = new FileOutputStream(file);
262       byte[] buf = new byte[256];
263       int read = -1;
264       while((read=is.read(buf))!=-1)
265       {
266         fos.write( buf,0,read);
267       }
268     }
269     catch(Exception JavaDoc e)
270     {
271       throw e;
272     }
273     finally
274     {
275       closeIgnoringExceptions( fos );
276       closeIgnoringExceptions( is );
277     }
278   }
279
280   static DecimalFormat JavaDoc format0 = new DecimalFormat JavaDoc("0.0");
281   public static String JavaDoc formatSize(long s)
282   {
283        if(s>1e9)
284        {
285           double gs = s/1.0e9;
286           if(gs<1.5)
287           {
288             return format0.format(gs)+" GB";
289           }
290           else
291           {
292              return ""+(int) Math.round(gs)+" GB";
293           }
294        }
295        if(s>1e6)
296        {
297           double ms = s/1.0e6;
298           if(ms<1.5)
299           {
300            return format0.format(ms)+" MB";
301           }
302           else
303           {
304              return ""+(int) Math.round(ms)+" MB";
305           }
306        }
307        else if(s>1e3)
308        {
309           double ks = s/1.0e3;
310           if(ks<1.5)
311           {
312            return format0.format(ks)+" kB";
313           }
314           else
315           {
316              return ""+(int) Math.round(ks)+" kB";
317           }
318
319        }
320        else
321        {
322          return s+" B";
323        }
324   }
325
326
327   public static long getSizeIncludingSubFiles(File root)
328   {
329     if(root.isFile()) return root.length();
330
331     Vector<File> all = new Vector<File>();
332     getAllFilesRecurse(root, all);
333
334     long tot = 0;
335     for(File f: all)
336     {
337       tot += f.length();
338     }
339     return tot;
340
341   }
342
343   public static void getAllFilesRecurse(File root, List<File> allFiles)
344   {
345    synchronized( FileUtils.getLockForFileAccess() )
346    {
347      if(!root.exists()) return;
348      if(root.isDirectory())
349      {
350        for(File fi: root.listFiles())
351        {
352          if(fi.isDirectory())
353          {
354             getAllFilesRecurse(fi, allFiles);
355          }
356          else
357          {
358             allFiles.add(fi);
359          }
360        }
361      }
362      else
363      {
364         allFiles.add(root);
365      }
366    }
367   }
368
369
370   public static int getNumberOfFiles(File root)
371   {
372      int count = 0;
373      if(!root.exists()) return 0;
374      if(root.isDirectory())
375      {
376        for(File f: root.listFiles())
377        {
378          if(f.isDirectory()) count += getNumberOfFiles(f);
379          else if(f.isFile())
380          {
381            count++;
382          }
383        }
384      }
385      else
386      {
387         return 1;
388      }
389      return count;
390   }
391
392   public static final void closeIgnoringExceptions(Closeable c)
393   {
394      try{
395        if(c!=null) c.close();
396      }
397      catch(Exception JavaDoc ignore) {} // nopmd
398
}
399
400 /** zipfile is not "closeable"
401 */

402   public static final void closeIgnoringExceptions(ZipFile c)
403   {
404      try{
405        if(c!=null) c.close();
406      }
407      catch(Exception JavaDoc ignore) {} // nopmd
408
}
409
410
411   /** with / as separator and a / at the end for directories
412   * CAUTION: case is NOT canonicalized. call first getCanonicalFileWithCase() on the file !
413   */

414   public static String JavaDoc getCanonicalName(File f)
415   {
416     String JavaDoc n = f.getAbsolutePath().replace("\\", "/");
417     if(f.isDirectory())
418     {
419       if(!n.endsWith("/"))
420       {
421         n+="/";
422       }
423     }
424     return n;
425   }
426
427   /** just calls the File.getCanonicalFile().
428   * The cases are corrected and ".." are "resolved".
429   * Should be called on each file object that is compared !
430   * Be very careful, E: and e: are denoting the same path on windows, but they string are not "equals"
431   */

432   public static File getCanonicalFileWithCase(File f)
433   {
434      try
435      {
436         return f.getCanonicalFile();
437      }
438      catch(Exception JavaDoc ign)
439      {
440         return f;
441      }
442   }
443 } // FileUtils
Popular Tags