1.1 restoration
[mir.git] / source / mir / util / FileFunctions.java
index bbbaa68..c9e6a10 100755 (executable)
  */
 package mir.util;
 
-import gnu.regexp.RE;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FilenameFilter;
-import java.io.IOException;
+import java.io.*;
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.List;
-import java.util.Vector;
+
+import gnu.regexp.RE;
 
 public class FileFunctions {
   protected static final int FILE_COPY_BUFFER_SIZE = 65536;
@@ -115,6 +109,46 @@ public class FileFunctions {
     }
   }
 
+  /**
+   * Copy the contents of an {@link InputStream} to a {@link File}
+   */
+  public static void copy(InputStream aSource, File aDestination) throws IOException {
+    BufferedOutputStream outputStream =
+        new BufferedOutputStream(new FileOutputStream(aDestination), 8192);
+
+    int read;
+    byte[] buf = new byte[8 * 1024];
+
+    while ((read = aSource.read(buf)) != -1) {
+      outputStream.write(buf, 0, read);
+    }
+
+    aSource.close();
+    outputStream.close();
+  }
+
+  /**
+   * Moves a {@link File} to a new location
+   */
+  public static void move(File aSource, File aDestination) throws IOException {
+    aDestination.getParentFile().mkdirs();
+    if (!aSource.renameTo(aDestination)) {
+      byte[] buffer = new byte[16384];
+      FileInputStream inputStream = new FileInputStream(aSource);
+      FileOutputStream outputStream = new FileOutputStream(aDestination);
+      try {
+        while (inputStream.read(buffer)>0) {
+          outputStream.write(buffer);
+        }
+      }
+      finally {
+        outputStream.close();
+        inputStream.close();
+      }
+      aSource.delete();
+    };
+  }
+
   public static class RegExpFileFilter implements FilenameFilter {
     private RE expression;
 
@@ -139,16 +173,36 @@ public class FileFunctions {
     public boolean accept(File aDir, String aName) {
       return new File(aDir, aName).isDirectory();
     }
-
   }
 
   public static List getDirectoryContentsAsList(File aDirectory, FilenameFilter aFilter) {
     Object[] contents = aDirectory.list(aFilter);
     if (contents==null)
-      return new Vector();
+      return Collections.EMPTY_LIST;
     else
       return Arrays.asList(contents);
   }
 
+  public static String getExtension(String aPath) {
+    int position = aPath.lastIndexOf('.');
+    if (position>=0) {
+      return aPath.substring(position+1);
+    }
+    else {
+      return "";
+    }
+  }
+
+  public static boolean isAbsolutePath(String aPath) {
+    return new File(aPath).isAbsolute();
+  }
 
+  public static File getAbsoluteOrRelativeFile(File aParentIfRelative, String aPath) {
+    if (isAbsolutePath(aPath)) {
+      return new File(aPath);
+    }
+    else {
+      return new File(aParentIfRelative, aPath);
+    }
+  }
 }
\ No newline at end of file