View Javadoc

1   package net.sf.cantina.util;
2   
3   import java.io.File;
4   import java.io.FileInputStream;
5   import java.io.FileOutputStream;
6   
7   /***
8    * @author Stephane JAIS
9    */
10  public abstract class FileUtils
11  {
12    public static boolean deleteDir(File dir)
13    {
14      if (dir.isDirectory())
15      {
16        String[] children = dir.list();
17        for (int i = 0; i < children.length; i++)
18        {
19          boolean success = deleteDir(new File(dir, children[i]));
20          if (!success)
21            return false;
22        }
23      }
24      return dir.delete();
25    }
26  
27    /***
28     * copy a file.
29     * @param source
30     * @param destination
31     * @param overwrite Should the destination be overwritten if exists?
32     * @return true if the file was written
33     * @throws Exception
34     */
35    public static boolean copyFile(String source, String destination, boolean overwrite)
36    throws Exception
37    {
38      File sourceFile = new File(source);
39      File destinationFile = new File(destination);
40      if (!sourceFile.exists())
41        throw new IllegalArgumentException("source file does not exist");
42      if (destinationFile.exists())
43      {
44        if (overwrite)
45          destinationFile.delete();
46        else
47          return false;
48      }
49      FileInputStream is = new FileInputStream(sourceFile);
50      FileOutputStream os = new FileOutputStream(destinationFile);
51      byte[] buf = new byte[1024];
52      int i = 0;
53      while((i=is.read(buf))!=-1)
54      {
55        os.write(buf, 0, i);
56      }
57      is.close();
58      os.close();
59      return true;
60    }
61  }