|
What this is
Other links
The source code/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.FileFilter; import java.io.OutputStream; import java.net.URL; import java.util.Collection; import java.util.Date; import org.apache.commons.io.filefilter.DirectoryFileFilter; import org.apache.commons.io.filefilter.FalseFileFilter; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.filefilter.SuffixFileFilter; import org.apache.commons.io.filefilter.TrueFileFilter; /** * This class provides basic facilities for manipulating files and file paths. * *
File-related methods** There are methods to create a {@link #toFile File from a URL}, copy a * {@link #copyFileToDirectory File to a directory}, * copy a {@link #copyFile File to another File}, * copy a {@link #copyURLToFile URL's contents to a File}, * as well as methods to {@link #deleteDirectory(File) delete} and {@link #cleanDirectory(File) * clean} a directory. * * * Common {@link java.io.File} manipulation routines. * *Origin of code*
Finds files within a given directory (and optionally its * subdirectories). All files found are filtered by an IOFileFilter. * *If your search should recurse into subdirectories you can pass in * an IOFileFilter for directories. You don't need to bind a * DirectoryFileFilter (via logical AND) to this filter. This method does * that for you. * *An example: If you want to search through all directories called
* "temp" you pass in Another common usage of this method is find files in a directory
* tree but ignoring the directories generated CVS. You can simply pass
* in Compare the contents of two files to determine if they are equal or not. *Code origin: Avalon * * @param file1 the first file * @param file2 the second file * @return true if the content of the files are equal or they both don't exist, false otherwise * @throws IOException in case of an I/O error */ public static boolean contentEquals(File file1, File file2) throws IOException { boolean file1Exists = file1.exists(); if (file1Exists != file2.exists()) { return false; } if (!file1Exists) { // two not existing files are equal return true; } if (file1.isDirectory() || file2.isDirectory()) { // don't want to compare directory contents throw new IOException("Can't compare directories, only files"); } InputStream input1 = null; InputStream input2 = null; try { input1 = new java.io.FileInputStream(file1); input2 = new java.io.FileInputStream(file2); return IOUtils.contentEquals(input1, input2); } finally { IOUtils.closeQuietly(input1); IOUtils.closeQuietly(input2); } } /** * Convert from aURL to a File .
* @param url File URL.
* @return The equivalent File object, or null if the URL's protocol
* is not file
*/
public static File toFile(URL url) {
if (url.getProtocol().equals("file") == false) {
return null;
} else {
String filename =
url.getFile().replace('/', File.separatorChar);
return new File(filename);
}
}
/**
* Convert the array of Files into a list of URLs.
*
* @param files the array of files
* @return the array of URLs
* @throws IOException if an error occurs
*/
public static URL[] toURLs(File[] files) throws IOException {
URL[] urls = new URL[files.length];
for (int i = 0; i < urls.length; i++) {
urls[i] = files[i].toURL();
}
return urls;
}
/**
* Copy file from source to destination. If destinationDirectory does not exist, it
* (and any parent directories) will be created. If a file source in
* destinationDirectory exists, it will be overwritten.
* The copy will have the same file date as the original.
*
* @param source An existing File to copy.
* @param destinationDirectory A directory to copy source into.
*
* @throws FileNotFoundException if source isn't a normal file.
* @throws IllegalArgumentException if destinationDirectory isn't a directory.
* @throws IOException if source does not exist, the file in
* destinationDirectory cannot be written to, or an IO error occurs during copying.
*/
public static void copyFileToDirectory(
File source,
File destinationDirectory)
throws IOException {
if (destinationDirectory.exists()
&& !destinationDirectory.isDirectory()) {
throw new IllegalArgumentException("Destination is not a directory");
}
copyFile(source, new File(destinationDirectory, source.getName()), true);
}
/**
* Copy file from source to destination. The directories up to
* destination will be created if they don't already exist.
* destination will be overwritten if it already exists.
* The copy will have the same file date as the original.
*
* @param source An existing non-directory File to copy
* bytes from.
* @param destination A non-directory File to write bytes to
* (possibly overwriting).
*
* @throws IOException if source does not exist, destination cannot be
* written to, or an IO error occurs during copying.
*
* @throws FileNotFoundException if destination is a directory
* (use {@link #copyFileToDirectory}).
*/
public static void copyFile(File source, File destination)
throws IOException {
copyFile(source, destination, true);
}
/**
* Copy file from source to destination. The directories up to
* destination will be created if they don't already exist.
* destination will be overwritten if it already exists.
*
* @param source An existing non-directory File to copy
* bytes from.
* @param destination A non-directory File to write bytes to
* (possibly overwriting).
* @param preserveFileDate True if the file date of the copy should be the
* same as the original.
*
* @throws IOException if source does not exist, destination cannot be
* written to, or an IO error occurs during copying.
*
* @throws FileNotFoundException if destination is a directory
* (use {@link #copyFileToDirectory}).
*/
public static void copyFile(File source, File destination, boolean preserveFileDate)
throws IOException {
//check source exists
if (!source.exists()) {
String message = "File " + source + " does not exist";
throw new FileNotFoundException(message);
}
//does destinations directory exist ?
if (destination.getParentFile() != null
&& !destination.getParentFile().exists()) {
destination.getParentFile().mkdirs();
}
//make sure we can write to destination
if (destination.exists() && !destination.canWrite()) {
String message =
"Unable to open file " + destination + " for writing.";
throw new IOException(message);
}
//makes sure it is not the same file
if (source.getCanonicalPath().equals(destination.getCanonicalPath())) {
String message =
"Unable to write file " + source + " on itself.";
throw new IOException(message);
}
FileInputStream input = new FileInputStream(source);
try {
FileOutputStream output = new FileOutputStream(destination);
try {
CopyUtils.copy(input, output);
} finally {
IOUtils.closeQuietly(output);
}
} finally {
IOUtils.closeQuietly(input);
}
if (source.length() != destination.length()) {
String message =
"Failed to copy full contents from "
+ source
+ " to "
+ destination;
throw new IOException(message);
}
if (preserveFileDate) {
//file copy should preserve file date
destination.setLastModified(source.lastModified());
}
}
/**
* Copies bytes from the URL source to a file destination .
* The directories up to destination will be created if they don't already exist.
* destination will be overwritten if it already exists.
*
* @param source A URL to copy bytes from.
* @param destination A non-directory File to write bytes to (possibly
* overwriting).
*
* @throws IOException if
*
* Reads the contents of a file into a String. * ** There is no readFileToString method without encoding parameter because * the default encoding can differ between platforms and therefore results * in inconsistent results. * * * @param file the file to read. * @param encoding the encoding to use * @return The file contents or null if read failed. * @throws IOException in case of an I/O error * @throws UnsupportedEncodingException if the encoding is not supported * by the VM */ public static String readFileToString( File file, String encoding) throws IOException { InputStream in = new java.io.FileInputStream(file); try { return IOUtils.toString(in, encoding); } finally { IOUtils.closeQuietly(in); } } /** ** Writes data to a file. The file will be created if it does not exist. * ** There is no readFileToString method without encoding parameter because * the default encoding can differ between platforms and therefore results * in inconsistent results. * * * @param file the file to write. * @param data The content to write to the file. * @param encoding encoding to use * @throws IOException in case of an I/O error * @throws UnsupportedEncodingException if the encoding is not supported * by the VM */ public static void writeStringToFile(File file, String data, String encoding) throws IOException { OutputStream out = new java.io.FileOutputStream(file); try { out.write(data.getBytes(encoding)); } finally { IOUtils.closeQuietly(out); } } /** ** Delete a file. If file is a directory, delete it and all sub-directories. * ** The difference between File.delete() and this method are: * *
File is newer than the reference
* File .
*
* @param file the File of which the modification date must be compared
* @param reference the File of which the modification date is used
* like reference
* @return true if the File exists and has been modified more recently
* than the reference File .
*/
public static boolean isFileNewer(File file, File reference) {
if (reference == null) {
throw new IllegalArgumentException("No specified reference file");
}
if (!reference.exists()) {
throw new IllegalArgumentException("The reference file '" + file + "' doesn't exist");
}
return isFileNewer(file, reference.lastModified());
}
/**
* Tests if the specified File is newer than the specified
* Date
*
* @param file the File of which the modification date must be compared
* @param date the date reference
* @return true if the File exists and has been modified after
* the given Date .
*/
public static boolean isFileNewer(File file, Date date) {
if (date == null) {
throw new IllegalArgumentException("No specified date");
}
return isFileNewer(file, date.getTime());
}
/**
* Tests if the specified File is newer than the specified
* time reference.
*
* @param file the File of which the modification date must be compared.
* @param timeMillis the time reference measured in milliseconds since the epoch
* (00:00:00 GMT, January 1, 1970)
* @return true if the File exists and has been modified after
* the given time reference.
*/
public static boolean isFileNewer(File file, long timeMillis) {
if (file == null) {
throw new IllegalArgumentException("No specified file");
}
if (!file.exists()) {
return false;
}
return file.lastModified() > timeMillis;
}
}
|
... this post is sponsored by my books ... | |
![]() #1 New Release! |
![]() FP Best Seller |
Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.