package za.co.enerweb.toolbox.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.AndFileFilter;
import org.apache.commons.io.filefilter.FalseFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.RegexFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
/**
* rather use org.apache.commons.io.IOUtils.class and
* org.apache.commons.io.FileUtils.class where possible
*/
public class FileUtils {
private static final Pattern NO_TILDES = Pattern.compile("^[^~]+$");
public static final int BUFFER_SIZE = 10000;
public static void copyDirectorySkipExistingFiles(final File srcDir,
final File destDir) throws IOException {
copyDirectorySkipExistingFiles(srcDir, destDir, null);
}
/**
* I could not find another util that implements this
* @param srcDir
* @param destDir if it does not exist, it will be created.
* @param filter gives you a way of not copying everything
* @throws IOException
*/
public static void copyDirectorySkipExistingFiles(final File srcDir,
final File destDir, final FilenameFilter filter) throws IOException {
if (!destDir.exists()) {
destDir.mkdirs();
}
if (!srcDir.isDirectory()) {
throw new IOException("Source is not a directory: "
+ srcDir.getAbsolutePath());
}
if (!destDir.isDirectory()) {
throw new IOException("Destination is not a directory: "
+ destDir.getAbsolutePath());
}
String[] fileList =
filter == null ? srcDir.list() : srcDir.list(filter);
for (String fileName : fileList) {
File srcFile = new File(srcDir, fileName);
File destFile = new File(destDir, fileName);
if (srcFile.isDirectory()) {
copyDirectorySkipExistingFiles(srcFile, destFile, filter);
} else if (!destFile.exists()) {
org.apache.commons.io.FileUtils.copyFile(srcFile, destFile);
}
}
}
/**
* @param str
* @return
* maybe look at using org.apache.commons.io.FilenameUtils
*/
public static String backslashes2ForwardSlashes(final String str) {
return str.replace('\\', '/');
}
/**
* Calculates the size of the file or the directory recuresively. returns
* the total ize in bytes.
* @param file_or_directory
* @return
* @deprecated use org.apache.commons.io.FileUtils.sizeOfDirectory or
* File.length
*/
@Deprecated
public static long calculateSizeRecursively(final File file_or_directory) {
if (file_or_directory.isDirectory()) {
return org.apache.commons.io.FileUtils
.sizeOfDirectory(file_or_directory);
} else {
return file_or_directory.length();
}
}
/**
* @param fileNameString
* @return
* @throws FileUtilsException
* @deprecated use org.apache.commons.io.filefilter.WildcardFileFilter
*/
@Deprecated
public static String convertWildCardFileNameStringToRegularExpression(
String fileNameString) throws FileUtilsException {
if (!fileNameString.matches("[0-9a-zA-Z \\*\\.\\?\\-_]*")) {
throw new FileUtilsException(
"Recieved an invalid fileNameString could be " +
"something like 'pre*post.txt'");
}
// escape special regular expression chars
fileNameString = fileNameString.replaceAll("\\.", "\\\\.");
fileNameString = fileNameString.replaceAll("\\-", "\\\\-");
// implement supported wildcard chars
fileNameString = fileNameString.replaceAll("\\*", ".*");
fileNameString = fileNameString.replaceAll("\\?", ".");
// DebugMode.debugOutPrintln(fileNameString);
return fileNameString;
}
/**
* @param inputFile
* @param outputFile
* @return
* @deprecated use org.apache.commons.io.FileUtils.copyFile
*/
@Deprecated
public static boolean copyFile(final File inputFile,
final File outputFile) {
try {
org.apache.commons.io.FileUtils.copyFile(inputFile, outputFile);
return true;
} catch (IOException exception) {
System.err.println("Could not copy file " + inputFile + " to "
+ outputFile);
exception.printStackTrace();
return false;
}
}
/**
* @param inputFile
* @param outputFile
* @return
* @deprecated use org.apache.commons.io.FileUtils.copyFile
*/
@Deprecated
public static boolean copyFile(final String inputFile,
final String outputFile) {
return copyFile(new File(inputFile), new File(outputFile));
}
/**
* @param sourceFile
* @param targetFile
* @return
* @deprecated use org.apache.commons.io.FileUtils.copyDirectory
*/
@Deprecated
public static boolean copyRecursively(final File sourceFile,
final File targetFile) {
try {
org.apache.commons.io.FileUtils.copyDirectory(sourceFile,
targetFile);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* recursively delete file or directory
* @param file_to_delete
* @return true if totaly succcessful
* @deprecated use org.apache.commons.io.FileUtils.deleteDirectory
*/
@Deprecated
public static boolean deleteRecursively(final File file_to_delete) {
return rm_rf(file_to_delete);
}
/**
* recursively delete file or directory
* @param file_to_delete_name
* @return true if totaly succcessful
* @deprecated use org.apache.commons.io.FileUtils.deleteDirectory
*/
@Deprecated
public static boolean deleteRecursively(
final String file_to_delete_name) {
return deleteRecursively(new File(file_to_delete_name));
}
/**
* @param startingDirectory
* @param fileNameString
* @param recurse
* @return
* @throws FileUtilsException
* @throws IOException
* @deprecated use org.apache.commons.io.FileUtils.listFiles
*/
@Deprecated
public static File[] findFiles(final File startingDirectory,
final String fileNameString, final boolean recurse)
throws FileUtilsException, IOException {
ArrayList allMatcingFiles = new ArrayList();
HashSet doneDirectories = new HashSet();
WildcardFileFilter filter = new WildcardFileFilter(fileNameString,
recurse);
findFiles(startingDirectory, fileNameString, recurse, allMatcingFiles,
doneDirectories, filter);
return (File[]) allMatcingFiles.toArray(new File[0]);
}
/**
* @param startingDirectory
* @param fileNameString
* @param recurse
* @param allMatcingFiles
* @param doneDirectories
* @param filter
* @throws FileUtilsException
* @throws IOException
* @deprecated use org.apache.commons.io.FileUtils.listFiles
*/
@Deprecated
private static void findFiles(final File startingDirectory,
final String fileNameString, final boolean recurse,
final ArrayList allMatcingFiles, final HashSet doneDirectories,
final WildcardFileFilter filter)
throws FileUtilsException, IOException {
// System.out.println("findFiles in "+ startingDirectory);
File[] matchingFiles = startingDirectory.listFiles(filter);
for (File matchingFile : matchingFiles) {
String canonicalPath = matchingFile.getCanonicalPath();
if (matchingFile.isDirectory()) {
if (!doneDirectories.contains(canonicalPath)) {
doneDirectories.add(canonicalPath);
if (recurse) {
findFiles(matchingFile, fileNameString, recurse,
allMatcingFiles, doneDirectories, filter);
}
}
} else {
allMatcingFiles.add(matchingFile);
}
}
}
/**
* Get human readable filesize
* @param byte_size
* @return
* @deprecated use org.apache.commons.io.FileUtils.byteCountToDisplaySize
*/
@Deprecated
public static String formatFileSize(final long byte_size) {
return formatFileSize(byte_size, 3);
}
/**
* Get human readable filesize
* @param byte_size
* @param max_decimal_places
* @return
* @deprecated use org.apache.commons.io.FileUtils.byteCountToDisplaySize
*/
@Deprecated
public static String formatFileSize(final long byte_size,
final int max_decimal_places) {
return org.apache.commons.io.FileUtils
.byteCountToDisplaySize(byte_size);
}
/**
* Attempt to return the canonical path of the given file, otherwise return
* its absolute path.
* @deprecated
* @deprecated use org.apache.commons.io.FileNameUtils.normalizes
*/
@Deprecated
public static String getFullPath(final File file) {
try {
return file.getCanonicalPath();
} catch (IOException ex) {
System.out.println("unable to obtain canonical path for " + file);
return file.getAbsolutePath();
}
}
/**
* @param file
* @return
* @throws FileNotFoundException
* @throws IOException
* @deprecated use org.apache.commons.io.FileUtils.readFileToByteArray
*/
@Deprecated
public static byte[] readBytes(final File file)
throws FileNotFoundException, IOException {
return org.apache.commons.io.FileUtils.readFileToByteArray(file);
}
/**
* @param inputStream
* @return
* @throws IOException
* @deprecated use org.apache.commons.io.IOUtils.toByteArray
*/
@Deprecated
public static byte[] readBytes(final InputStream inputStream)
throws IOException {
return IOUtils.toByteArray(inputStream);
}
/**
* @param file_name
* @return
* @throws FileNotFoundException
* @throws IOException
* @deprecated use org.apache.commons.io.FileUtils.readFileToByteArray
*/
@Deprecated
public static byte[] readBytes(final String file_name)
throws FileNotFoundException, IOException {
return readBytes(new FileInputStream(file_name));
}
/**
* @param resourcePath eg. "za/co/enerweb/Test.class"
* @return the resource as a stream, but null if it could not be found.
* @throws IOException
* @deprecated Use {@link ResourceUtils#readResourceAsBytes(String)} instead
*/
@Deprecated
public static byte[] readResourceAsBytes(final String resourcePath)
throws IOException {
return ResourceUtils.getResourceAsBytes(resourcePath);
}
/**
* @param resourcePath eg. "za/co/enerweb/Test.class"
* @return the resource as a stream, but null if it could not be found.
* @throws IOException
* @deprecated Use {@link ResourceUtils#getResourceAsString(String)} instead
*/
@Deprecated
public static String readResourceAsString(final String resourcePath)
throws IOException {
return ResourceUtils.getResourceAsString(resourcePath);
}
/**
* Read the contents of a file as a String
* @param file
* @return
* @throws FileNotFoundException
* @throws IOException
* @deprecated use org.apache.commons.io.FileUtils.readFileToString
*/
@Deprecated
public static String readString(final File file)
throws FileNotFoundException, IOException {
return org.apache.commons.io.FileUtils.readFileToString(file);
}
/**
* Read an inputStream as a String
* @param stream
* @return
* @throws IOException
* @deprecated use org.apache.commons.io.IOUtils.toString
*/
@Deprecated
public static String readString(final InputStream stream)
throws IOException {
return IOUtils.toString(stream);
}
/**
* @param reader
* @return
* @throws IOException
* @deprecated use org.apache.commons.io.IOUtils.toString
*/
@Deprecated
public static String readString(final Reader reader) throws IOException {
return IOUtils.toString(reader);
}
/**
* recursively delete file or directory
* @param file_to_delete
* @return true if totaly succcessful
* @deprecated use org.apache.commons.io.FileUtils.deleteDirectory
*/
@Deprecated
public static boolean rm_rf(final File file_to_delete) {
return org.apache.commons.io.FileUtils.deleteQuietly(file_to_delete);
}
/**
* Write a String to a file (spawns a thread that writes data until
* finished)
* @param file
* @param string
* @return
* @throws IOException
* @deprecated use org.apache.commons.io.FileUtils.writeStringToFile
*/
@Deprecated
public static Thread writeStringToFile(final File file, final String string)
throws IOException {
org.apache.commons.io.FileUtils.writeStringToFile(file, string);
// avoid null pointer exception on old code
Thread thread = new Thread();
thread.setDaemon(true);
thread.start();
return thread;
}
/**
* Write a String to a outputStream (spawns a thread that writes data until
* finished)
* @param stream
* @param string
* @return
* @throws IOException
* @deprecated use org.apache.commons.io.IOUtils.write
*/
@Deprecated
public static Thread writeStringToStream(final OutputStream stream,
final String string) throws IOException {
IOUtils.write(string, stream);
// avoid null pointer exception on old code
Thread thread = new Thread();
thread.setDaemon(true);
thread.start();
return thread;
}
/**
* Finds files within a given directory (and optionally its subdirectories)
* which match an array of extensions.
* Modified from commons IO Utils, to be able to ignore files and folders
* that include ~
* @param directory the directory to search in
* @param extensions an array of extensions, ex. {"java","xml"}. If this
* parameter is <code>null</code>, all files are returned.
* @param recursive if true all subdirectories are searched as well
* @return an collection of java.io.File with the matching files
*/
public static Collection<File> listFiles(
File directory, String[] extensions, boolean recursive) {
IOFileFilter filter;
if (extensions == null) {
filter = TrueFileFilter.INSTANCE;
} else {
String[] suffixes = toSuffixes(extensions);
filter = new SuffixFileFilter(suffixes);
}
RegexFileFilter noTildes = new RegexFileFilter(NO_TILDES);
return org.apache.commons.io.FileUtils.listFiles(directory,
new AndFileFilter(filter, noTildes),
(recursive ? noTildes : FalseFileFilter.INSTANCE));
}
/**
* Converts an array of file extensions to suffixes for use
* with IOFileFilters.
* From commons IO Utils
*
* @param extensions an array of extensions. Format: {"java", "xml"}
* @return an array of suffixes. Format: {".java", ".xml"}
*/
private static String[] toSuffixes(String[] extensions) {
String[] suffixes = new String[extensions.length];
for (int i = 0; i < extensions.length; i++) {
suffixes[i] = "." + extensions[i];
}
return suffixes;
}
/**
* @param srcFile
* @param destDir
* @return The newly created file
*/
public static File copyFileToDirectory(File srcFile, File destDir)
throws IOException {
org.apache.commons.io.FileUtils.copyFileToDirectory(srcFile, destDir);
return new File(destDir, srcFile.getName());
}
}