001 package com.basilv.core;
002
003
004 import java.io.File;
005 import java.io.IOException;
006
007 /**
008 * Contains utility methods for working with Files.
009 */
010 public class FileUtilities
011 {
012
013 /**
014 * Return the canonical path, or the absolute path if an error occurs.
015 * @param file Cannot be null.
016 * @return the full path of the file.
017 */
018 public static String getCanonicalPath(File file) {
019 Assert.notNull("file", file);
020 try {
021 return file.getCanonicalPath();
022 } catch (IOException e) {
023 return file.getAbsolutePath();
024 }
025 }
026
027
028 /**
029 * Delete the specified directory and all its contents.
030 * @param file Cannot be null. If a file is specified, it is deleted.
031 */
032 public static void deleteRecursively(File file) {
033 Assert.notNull("file", file);
034
035 if (file.isDirectory()) {
036 File[] files = file.listFiles();
037 for (int i = 0; i < files.length; i++) {
038 deleteRecursively(files[i]);
039 }
040 }
041 deleteFile(file);
042 }
043
044 public static void deleteFile(File file) {
045 Assert.notNull("file", file);
046
047 if (!file.delete()) {
048 // Perhaps we couldn't delete the file because it no longer exists.
049 if (file.exists()) {
050 throw new RuntimeException("Unable to delete file '" + FileUtilities.getCanonicalPath(file) + "'.");
051 }
052 }
053
054 }
055 }