All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.testifyproject.apache.commons.io.FileUtils Maven / Gradle / Ivy

There is a newer version: 1.0.0
Show newest version
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in org.testifyproject.testifyprojectpliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org.testifyproject/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.testifyproject.apache.org.testifyproject.testifyprojectmons.org.testifyproject.testifyproject;

import java.org.testifyproject.testifyproject.File;
import java.org.testifyproject.testifyproject.FileFilter;
import java.org.testifyproject.testifyproject.FileInputStream;
import java.org.testifyproject.testifyproject.FileNotFoundException;
import java.org.testifyproject.testifyproject.FileOutputStream;
import java.org.testifyproject.testifyproject.IOException;
import java.org.testifyproject.testifyproject.InputStream;
import java.org.testifyproject.testifyproject.InputStreamReader;
import java.org.testifyproject.testifyproject.OutputStream;
import java.org.testifyproject.testifyproject.Reader;
import java.org.testifyproject.testifyproject.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.Checksum;

import org.testifyproject.apache.org.testifyproject.testifyprojectmons.org.testifyproject.testifyproject.filefilter.DirectoryFileFilter;
import org.testifyproject.apache.org.testifyproject.testifyprojectmons.org.testifyproject.testifyproject.filefilter.FalseFileFilter;
import org.testifyproject.apache.org.testifyproject.testifyprojectmons.org.testifyproject.testifyproject.filefilter.FileFilterUtils;
import org.testifyproject.apache.org.testifyproject.testifyprojectmons.org.testifyproject.testifyproject.filefilter.IOFileFilter;
import org.testifyproject.apache.org.testifyproject.testifyprojectmons.org.testifyproject.testifyproject.filefilter.SuffixFileFilter;
import org.testifyproject.apache.org.testifyproject.testifyprojectmons.org.testifyproject.testifyproject.filefilter.TrueFileFilter;
import org.testifyproject.apache.org.testifyproject.testifyprojectmons.org.testifyproject.testifyproject.output.NullOutputStream;

/**
 * General file manipulation utilities.
 * 

* Facilities are provided in the following areas: *

    *
  • writing to a file *
  • reading from a file *
  • make a directory including parent directories *
  • copying files and directories *
  • org.testifyproject.testifyprojectleting files and directories *
  • converting to and from a URL *
  • listing files and directories by filter and extension *
  • org.testifyproject.testifyprojectparing file content *
  • file last changed date *
  • calculating a checksum *
*

* Origin of code: Excalibur, Alexandria, Commons-Utils * * @version $Id: FileUtils.java 1307462 2012-03-30 15:13:11Z ggregory $ */ public class FileUtils { /** * Instances should NOT be constructed in standard programming. */ public FileUtils() { super(); } /** * The number of bytes in a kilobyte. */ public static final long ONE_KB = 1024; /** * The number of bytes in a megabyte. */ public static final long ONE_MB = ONE_KB * ONE_KB; /** * The file copy buffer size (30 MB) */ private static final long FILE_COPY_BUFFER_SIZE = ONE_MB * 30; /** * The number of bytes in a gigabyte. */ public static final long ONE_GB = ONE_KB * ONE_MB; /** * The number of bytes in a terabyte. */ public static final long ONE_TB = ONE_KB * ONE_GB; /** * The number of bytes in a petabyte. */ public static final long ONE_PB = ONE_KB * ONE_TB; /** * The number of bytes in an exabyte. */ public static final long ONE_EB = ONE_KB * ONE_PB; /** * The number of bytes in a zettabyte. */ public static final BigInteger ONE_ZB = BigInteger.valueOf(ONE_KB).multiply(BigInteger.valueOf(ONE_EB)); /** * The number of bytes in a yottabyte. */ public static final BigInteger ONE_YB = ONE_ZB.multiply(BigInteger.valueOf(ONE_EB)); /** * An empty array of type File. */ public static final File[] EMPTY_FILE_ARRAY = new File[0]; /** * The UTF-8 character set, used to org.testifyproject.testifyprojectcode octets in URLs. */ private static final Charset UTF8 = Charset.forName("UTF-8"); //----------------------------------------------------------------------- /** * Construct a file from the set of name elements. * * @param directory the parent directory * @param names the name elements * @return the file * @since 2.1 */ public static File getFile(File directory, String... names) { if (directory == null) { throw new NullPointerException("directorydirectory must not be null"); } if (names == null) { throw new NullPointerException("names must not be null"); } File file = directory; for (String name : names) { file = new File(file, name); } return file; } /** * Construct a file from the set of name elements. * * @param names the name elements * @return the file * @since 2.1 */ public static File getFile(String... names) { if (names == null) { throw new NullPointerException("names must not be null"); } File file = null; for (String name : names) { if (file == null) { file = new File(name); } else { file = new File(file, name); } } return file; } /** * Returns the path to the system temporary directory. * * @return the path to the system temporary directory. * * @since 2.0 */ public static String getTempDirectoryPath() { return System.getProperty("java.org.testifyproject.testifyproject.tmpdir"); } /** * Returns a {@link File} representing the system temporary directory. * * @return the system temporary directory. * * @since 2.0 */ public static File getTempDirectory() { return new File(getTempDirectoryPath()); } /** * Returns the path to the user's home directory. * * @return the path to the user's home directory. * * @since 2.0 */ public static String getUserDirectoryPath() { return System.getProperty("user.home"); } /** * Returns a {@link File} representing the user's home directory. * * @return the user's home directory. * * @since 2.0 */ public static File getUserDirectory() { return new File(getUserDirectoryPath()); } //----------------------------------------------------------------------- /** * Opens a {@link FileInputStream} for the specified file, providing better * error messages than simply calling new FileInputStream(file). *

* At the end of the method either the stream will be successfully opened, * or an exception will have been thrown. *

* An exception is thrown if the file does not exist. * An exception is thrown if the file object exists but is a directory. * An exception is thrown if the file exists but cannot be read. * * @param file the file to open for input, must not be {@code null} * @return a new {@link FileInputStream} for the specified file * @throws FileNotFoundException if the file does not exist * @throws IOException if the file object is a directory * @throws IOException if the file cannot be read * @since 1.3 */ public static FileInputStream openInputStream(File file) throws IOException { if (file.exists()) { if (file.isDirectory()) { throw new IOException("File '" + file + "' exists but is a directory"); } if (file.canRead() == false) { throw new IOException("File '" + file + "' cannot be read"); } } else { throw new FileNotFoundException("File '" + file + "' does not exist"); } return new FileInputStream(file); } //----------------------------------------------------------------------- /** * Opens a {@link FileOutputStream} for the specified file, checking and * creating the parent directory if it does not exist. *

* At the end of the method either the stream will be successfully opened, * or an exception will have been thrown. *

* The parent directory will be created if it does not exist. * The file will be created if it does not exist. * An exception is thrown if the file object exists but is a directory. * An exception is thrown if the file exists but cannot be written to. * An exception is thrown if the parent directory cannot be created. * * @param file the file to open for output, must not be {@code null} * @return a new {@link FileOutputStream} for the specified file * @throws IOException if the file object is a directory * @throws IOException if the file cannot be written to * @throws IOException if a parent directory needs creating but that fails * @since 1.3 */ public static FileOutputStream openOutputStream(File file) throws IOException { return openOutputStream(file, false); } /** * Opens a {@link FileOutputStream} for the specified file, checking and * creating the parent directory if it does not exist. *

* At the end of the method either the stream will be successfully opened, * or an exception will have been thrown. *

* The parent directory will be created if it does not exist. * The file will be created if it does not exist. * An exception is thrown if the file object exists but is a directory. * An exception is thrown if the file exists but cannot be written to. * An exception is thrown if the parent directory cannot be created. * * @param file the file to open for output, must not be {@code null} * @param append if {@code true}, then bytes will be added to the * end of the file rather than overwriting * @return a new {@link FileOutputStream} for the specified file * @throws IOException if the file object is a directory * @throws IOException if the file cannot be written to * @throws IOException if a parent directory needs creating but that fails * @since 2.1 */ public static FileOutputStream openOutputStream(File file, boolean append) throws IOException { if (file.exists()) { if (file.isDirectory()) { throw new IOException("File '" + file + "' exists but is a directory"); } if (file.canWrite() == false) { throw new IOException("File '" + file + "' cannot be written to"); } } else { File parent = file.getParentFile(); if (parent != null) { if (!parent.mkdirs() && !parent.isDirectory()) { throw new IOException("Directory '" + parent + "' could not be created"); } } } return new FileOutputStream(file, append); } //----------------------------------------------------------------------- /** * Returns a human-readable version of the file size, where the input * represents a specific number of bytes. * * If the size is over 1GB, the size is returned as the number of whole GB, * i.e. the size is rounded down to the nearest GB boundary. * * Similarly for the 1MB and 1KB boundaries. * * @param size the number of bytes * @return a human-readable display value (includes units - GB, MB, KB or bytes) */ // See https://issues.apache.org.testifyproject/jira/browse/IO-226 - should the rounding be changed? public static String byteCountToDisplaySize(long size) { String displaySize; if (size / ONE_EB > 0) { displaySize = String.valueOf(size / ONE_EB) + " EB"; } else if (size / ONE_PB > 0) { displaySize = String.valueOf(size / ONE_PB) + " PB"; } else if (size / ONE_TB > 0) { displaySize = String.valueOf(size / ONE_TB) + " TB"; } else if (size / ONE_GB > 0) { displaySize = String.valueOf(size / ONE_GB) + " GB"; } else if (size / ONE_MB > 0) { displaySize = String.valueOf(size / ONE_MB) + " MB"; } else if (size / ONE_KB > 0) { displaySize = String.valueOf(size / ONE_KB) + " KB"; } else { displaySize = String.valueOf(size) + " bytes"; } return displaySize; } //----------------------------------------------------------------------- /** * Implements the same behaviour as the "touch" utility on Unix. It creates * a new file with size 0 or, if the file exists already, it is opened and * closed without modifying it, but updating the file date and time. *

* NOTE: As from v1.3, this method throws an IOException if the last * modified date of the file cannot be set. Also, as from v1.3 this method * creates parent directories if they do not exist. * * @param file the File to touch * @throws IOException If an I/O problem occurs */ public static void touch(File file) throws IOException { if (!file.exists()) { OutputStream out = openOutputStream(file); IOUtils.closeQuietly(out); } boolean success = file.setLastModified(System.currentTimeMillis()); if (!success) { throw new IOException("Unable to set the last modification time for " + file); } } //----------------------------------------------------------------------- /** * Converts a Collection containing java.org.testifyproject.testifyproject.File instanced into array * representation. This is to account for the difference between * File.listFiles() and FileUtils.listFiles(). * * @param files a Collection containing java.org.testifyproject.testifyproject.File instances * @return an array of java.org.testifyproject.testifyproject.File */ public static File[] convertFileCollectionToFileArray(Collection files) { return files.toArray(new File[files.size()]); } //----------------------------------------------------------------------- /** * Finds files within a given directory (and optionally its * subdirectories). All files found are filtered by an IOFileFilter. * * @param files the collection of files found. * @param directory the directory to search in. * @param filter the filter to apply to files and directories. * @param includeSubDirectories indicates if will include the subdirectories themselves */ private static void innerListFiles(Collection files, File directory, IOFileFilter filter, boolean includeSubDirectories) { File[] found = directory.listFiles((FileFilter) filter); if (found != null) { for (File file : found) { if (file.isDirectory()) { if (includeSubDirectories) { files.add(file); } innerListFiles(files, file, filter, includeSubDirectories); } else { files.add(file); } } } } /** * 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 FileFilterUtils.NameFileFilter("temp") *

* Another org.testifyproject.testifyprojectmon usage of this method is find files in a directory * tree but ignoring the directories generated CVS. You can simply pass * in FileFilterUtils.makeCVSAware(null). * * @param directory the directory to search in * @param fileFilter filter to apply when finding files. * @param dirFilter optional filter to apply when finding subdirectories. * If this parameter is {@code null}, subdirectories will not be included in the * search. Use TrueFileFilter.INSTANCE to match all directories. * @return an collection of java.org.testifyproject.testifyproject.File with the matching files * @see org.testifyproject.apache.org.testifyproject.testifyprojectmons.org.testifyproject.testifyproject.filefilter.FileFilterUtils * @see org.testifyproject.apache.org.testifyproject.testifyprojectmons.org.testifyproject.testifyproject.filefilter.NameFileFilter */ public static Collection listFiles( File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) { validateListFilesParameters(directory, fileFilter); IOFileFilter effFileFilter = setUpEffectiveFileFilter(fileFilter); IOFileFilter effDirFilter = setUpEffectiveDirFilter(dirFilter); //Find files Collection files = new java.util.LinkedList(); innerListFiles(files, directory, FileFilterUtils.or(effFileFilter, effDirFilter), false); return files; } /** * Validates the given arguments. *

    *
  • Throws {@link IllegalArgumentException} if {@code directory} is not a directory
  • *
  • Throws {@link NullPointerException} if {@code fileFilter} is null
  • *
* * @param directory The File to test * @param fileFilter The IOFileFilter to test */ private static void validateListFilesParameters(File directory, IOFileFilter fileFilter) { if (!directory.isDirectory()) { throw new IllegalArgumentException("Parameter 'directory' is not a directory"); } if (fileFilter == null) { throw new NullPointerException("Parameter 'fileFilter' is null"); } } /** * Returns a filter that accepts files in addition to the {@link File} objects accepted by the given filter. * * @param fileFilter a base filter to add to * @return a filter that accepts files */ private static IOFileFilter setUpEffectiveFileFilter(IOFileFilter fileFilter) { return FileFilterUtils.and(fileFilter, FileFilterUtils.notFileFilter(DirectoryFileFilter.INSTANCE)); } /** * Returns a filter that accepts directories in addition to the {@link File} objects accepted by the given filter. * * @param dirFilter a base filter to add to * @return a filter that accepts directories */ private static IOFileFilter setUpEffectiveDirFilter(IOFileFilter dirFilter) { return dirFilter == null ? FalseFileFilter.INSTANCE : FileFilterUtils.and(dirFilter, DirectoryFileFilter.INSTANCE); } /** * Finds files within a given directory (and optionally its * subdirectories). All files found are filtered by an IOFileFilter. *

* The resulting collection includes the subdirectories themselves. *

* @see org.testifyproject.apache.org.testifyproject.testifyprojectmons.org.testifyproject.testifyproject.FileUtils#listFiles * * @param directory the directory to search in * @param fileFilter filter to apply when finding files. * @param dirFilter optional filter to apply when finding subdirectories. * If this parameter is {@code null}, subdirectories will not be included in the * search. Use TrueFileFilter.INSTANCE to match all directories. * @return an collection of java.org.testifyproject.testifyproject.File with the matching files * @see org.testifyproject.apache.org.testifyproject.testifyprojectmons.org.testifyproject.testifyproject.filefilter.FileFilterUtils * @see org.testifyproject.apache.org.testifyproject.testifyprojectmons.org.testifyproject.testifyproject.filefilter.NameFileFilter * @since 2.2 */ public static Collection listFilesAndDirs( File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) { validateListFilesParameters(directory, fileFilter); IOFileFilter effFileFilter = setUpEffectiveFileFilter(fileFilter); IOFileFilter effDirFilter = setUpEffectiveDirFilter(dirFilter); //Find files Collection files = new java.util.LinkedList(); if (directory.isDirectory()) { files.add(directory); } innerListFiles(files, directory, FileFilterUtils.or(effFileFilter, effDirFilter), true); return files; } /** * Allows iteration over the files in given directory (and optionally * its subdirectories). *

* All files found are filtered by an IOFileFilter. This method is * based on {@link #listFiles(File, IOFileFilter, IOFileFilter)}, * which supports Iterable ('foreach' loop). *

* @param directory the directory to search in * @param fileFilter filter to apply when finding files. * @param dirFilter optional filter to apply when finding subdirectories. * If this parameter is {@code null}, subdirectories will not be included in the * search. Use TrueFileFilter.INSTANCE to match all directories. * @return an iterator of java.org.testifyproject.testifyproject.File for the matching files * @see org.testifyproject.apache.org.testifyproject.testifyprojectmons.org.testifyproject.testifyproject.filefilter.FileFilterUtils * @see org.testifyproject.apache.org.testifyproject.testifyprojectmons.org.testifyproject.testifyproject.filefilter.NameFileFilter * @since 1.2 */ public static Iterator iterateFiles( File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) { return listFiles(directory, fileFilter, dirFilter).iterator(); } /** * Allows iteration over the files in given directory (and optionally * its subdirectories). *

* All files found are filtered by an IOFileFilter. This method is * based on {@link #listFilesAndDirs(File, IOFileFilter, IOFileFilter)}, * which supports Iterable ('foreach' loop). *

* The resulting iterator includes the subdirectories themselves. * * @param directory the directory to search in * @param fileFilter filter to apply when finding files. * @param dirFilter optional filter to apply when finding subdirectories. * If this parameter is {@code null}, subdirectories will not be included in the * search. Use TrueFileFilter.INSTANCE to match all directories. * @return an iterator of java.org.testifyproject.testifyproject.File for the matching files * @see org.testifyproject.apache.org.testifyproject.testifyprojectmons.org.testifyproject.testifyproject.filefilter.FileFilterUtils * @see org.testifyproject.apache.org.testifyproject.testifyprojectmons.org.testifyproject.testifyproject.filefilter.NameFileFilter * @since 2.2 */ public static Iterator iterateFilesAndDirs(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) { return listFilesAndDirs(directory, fileFilter, dirFilter).iterator(); } //----------------------------------------------------------------------- /** * Converts an array of file extensions to suffixes for use * with IOFileFilters. * * @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; } /** * Finds files within a given directory (and optionally its subdirectories) * which match an array of extensions. * * @param directory the directory to search in * @param extensions an array of extensions, ex. {"java","xml"}. If this * parameter is {@code null}, all files are returned. * @param recursive if true all subdirectories are searched as well * @return an collection of java.org.testifyproject.testifyproject.File with the matching files */ public static Collection listFiles( File directory, String[] extensions, boolean recursive) { IOFileFilter filter; if (extensions == null) { filter = TrueFileFilter.INSTANCE; } else { String[] suffixes = toSuffixes(extensions); filter = new SuffixFileFilter(suffixes); } return listFiles(directory, filter, recursive ? TrueFileFilter.INSTANCE : FalseFileFilter.INSTANCE); } /** * Allows iteration over the files in a given directory (and optionally * its subdirectories) which match an array of extensions. This method * is based on {@link #listFiles(File, String[], boolean)}, * which supports Iterable ('foreach' loop). * * @param directory the directory to search in * @param extensions an array of extensions, ex. {"java","xml"}. If this * parameter is {@code null}, all files are returned. * @param recursive if true all subdirectories are searched as well * @return an iterator of java.org.testifyproject.testifyproject.File with the matching files * @since 1.2 */ public static Iterator iterateFiles( File directory, String[] extensions, boolean recursive) { return listFiles(directory, extensions, recursive).iterator(); } //----------------------------------------------------------------------- /** * Compares the contents of two files to org.testifyproject.testifyprojecttermine if they are equal or not. *

* This method checks to see if the two files are different lengths * or if they point to the same file, before resorting to byte-by-byte * org.testifyproject.testifyprojectparison of the contents. *

* 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 org.testifyproject.testifyprojectpare directory contents throw new IOException("Can't org.testifyproject.testifyprojectpare directories, only files"); } if (file1.length() != file2.length()) { // lengths differ, cannot be equal return false; } if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) { // same file return true; } InputStream input1 = null; InputStream input2 = null; try { input1 = new FileInputStream(file1); input2 = new FileInputStream(file2); return IOUtils.contentEquals(input1, input2); } finally { IOUtils.closeQuietly(input1); IOUtils.closeQuietly(input2); } } //----------------------------------------------------------------------- /** * Compares the contents of two files to org.testifyproject.testifyprojecttermine if they are equal or not. *

* This method checks to see if the two files point to the same file, * before resorting to line-by-line org.testifyproject.testifyprojectparison of the contents. *

* * @param file1 the first file * @param file2 the second file * @param charsetName the character encoding to be used. * May be null, in which case the platform org.testifyproject.testifyprojectfault is used * @return true if the content of the files are equal or neither exists, * false otherwise * @throws IOException in case of an I/O error * @since 2.2 * @see IOUtils#contentEqualsIgnoreEOL(Reader, Reader) */ public static boolean contentEqualsIgnoreEOL(File file1, File file2, String charsetName) 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 org.testifyproject.testifyprojectpare directory contents throw new IOException("Can't org.testifyproject.testifyprojectpare directories, only files"); } if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) { // same file return true; } Reader input1 = null; Reader input2 = null; try { if (charsetName == null) { input1 = new InputStreamReader(new FileInputStream(file1)); input2 = new InputStreamReader(new FileInputStream(file2)); } else { input1 = new InputStreamReader(new FileInputStream(file1), charsetName); input2 = new InputStreamReader(new FileInputStream(file2), charsetName); } return IOUtils.contentEqualsIgnoreEOL(input1, input2); } finally { IOUtils.closeQuietly(input1); IOUtils.closeQuietly(input2); } } //----------------------------------------------------------------------- /** * Convert from a URL to a File. *

* From version 1.1 this method will org.testifyproject.testifyprojectcode the URL. * Syntax such as file:///my%20docs/file.txt will be * correctly org.testifyproject.testifyprojectcoded to /my docs/file.txt. Starting with version * 1.5, this method uses UTF-8 to org.testifyproject.testifyprojectcode percent-encoded octets to characters. * Additionally, malformed percent-encoded octets are handled leniently by * passing them through literally. * * @param url the file URL to convert, {@code null} returns {@code null} * @return the equivalent File object, or {@code null} * if the URL's protocol is not file */ public static File toFile(URL url) { if (url == null || !"file".equalsIgnoreCase(url.getProtocol())) { return null; } else { String filename = url.getFile().replace('/', File.separatorChar); filename = org.testifyproject.testifyprojectcodeUrl(filename); return new File(filename); } } /** * Decodes the specified URL as per RFC 3986, i.e. transforms * percent-encoded octets to characters by org.testifyproject.testifyprojectcoding with the UTF-8 character * set. This function is primarily intended for usage with * {@link java.net.URL} which unfortunately does not enforce proper URLs. As * such, this method will leniently accept invalid characters or malformed * percent-encoded octets and simply pass them literally through to the * result string. Except for rare edge cases, this will make unencoded URLs * pass through unaltered. * * @param url The URL to org.testifyproject.testifyprojectcode, may be {@code null}. * @return The org.testifyproject.testifyprojectcoded URL or {@code null} if the input was * {@code null}. */ static String org.testifyproject.testifyprojectcodeUrl(String url) { String org.testifyproject.testifyprojectcoded = url; if (url != null && url.indexOf('%') >= 0) { int n = url.length(); StringBuffer buffer = new StringBuffer(); ByteBuffer bytes = ByteBuffer.allocate(n); for (int i = 0; i < n;) { if (url.charAt(i) == '%') { try { do { byte octet = (byte) Integer.parseInt(url.substring(i + 1, i + 3), 16); bytes.put(octet); i += 3; } while (i < n && url.charAt(i) == '%'); continue; } catch (RuntimeException e) { // malformed percent-encoded octet, fall through and // append characters literally } finally { if (bytes.position() > 0) { bytes.flip(); buffer.append(UTF8.org.testifyproject.testifyprojectcode(bytes).toString()); bytes.clear(); } } } buffer.append(url.charAt(i++)); } org.testifyproject.testifyprojectcoded = buffer.toString(); } return org.testifyproject.testifyprojectcoded; } /** * Converts each of an array of URL to a File. *

* Returns an array of the same size as the input. * If the input is {@code null}, an empty array is returned. * If the input contains {@code null}, the output array contains {@code null} at the same * index. *

* This method will org.testifyproject.testifyprojectcode the URL. * Syntax such as file:///my%20docs/file.txt will be * correctly org.testifyproject.testifyprojectcoded to /my docs/file.txt. * * @param urls the file URLs to convert, {@code null} returns empty array * @return a non-{@code null} array of Files matching the input, with a {@code null} item * if there was a {@code null} at that index in the input array * @throws IllegalArgumentException if any file is not a URL file * @throws IllegalArgumentException if any file is incorrectly encoded * @since 1.1 */ public static File[] toFiles(URL[] urls) { if (urls == null || urls.length == 0) { return EMPTY_FILE_ARRAY; } File[] files = new File[urls.length]; for (int i = 0; i < urls.length; i++) { URL url = urls[i]; if (url != null) { if (url.getProtocol().equals("file") == false) { throw new IllegalArgumentException( "URL could not be converted to a File: " + url); } files[i] = toFile(url); } } return files; } /** * Converts each of an array of File to a URL. *

* Returns an array of the same size as the input. * * @param files the files to convert * @return an array of URLs matching the input * @throws IOException if a file cannot be converted */ 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].toURI().toURL(); } return urls; } //----------------------------------------------------------------------- /** * Copies a file to a directory preserving the file date. *

* This method copies the contents of the specified source file * to a file of the same name in the specified org.testifyproject.testifyprojectstination directory. * The org.testifyproject.testifyprojectstination directory is created if it does not exist. * If the org.testifyproject.testifyprojectstination file exists, then this method will overwrite it. *

* Note: This method tries to preserve the file's last * modified date/times using {@link File#setLastModified(long)}, however * it is not guaranteed that the operation will succeed. * If the modification operation fails, no indication is provided. * * @param srcFile an existing file to copy, must not be {@code null} * @param org.testifyproject.testifyprojectstDir the directory to place the copy in, must not be {@code null} * * @throws NullPointerException if source or org.testifyproject.testifyprojectstination is null * @throws IOException if source or org.testifyproject.testifyprojectstination is invalid * @throws IOException if an IO error occurs during copying * @see #copyFile(File, File, boolean) */ public static void copyFileToDirectory(File srcFile, File org.testifyproject.testifyprojectstDir) throws IOException { copyFileToDirectory(srcFile, org.testifyproject.testifyprojectstDir, true); } /** * Copies a file to a directory optionally preserving the file date. *

* This method copies the contents of the specified source file * to a file of the same name in the specified org.testifyproject.testifyprojectstination directory. * The org.testifyproject.testifyprojectstination directory is created if it does not exist. * If the org.testifyproject.testifyprojectstination file exists, then this method will overwrite it. *

* Note: Setting preserveFileDate to * {@code true} tries to preserve the file's last modified * date/times using {@link File#setLastModified(long)}, however it is * not guaranteed that the operation will succeed. * If the modification operation fails, no indication is provided. * * @param srcFile an existing file to copy, must not be {@code null} * @param org.testifyproject.testifyprojectstDir the directory to place the copy in, must not be {@code null} * @param preserveFileDate true if the file date of the copy * should be the same as the original * * @throws NullPointerException if source or org.testifyproject.testifyprojectstination is {@code null} * @throws IOException if source or org.testifyproject.testifyprojectstination is invalid * @throws IOException if an IO error occurs during copying * @see #copyFile(File, File, boolean) * @since 1.3 */ public static void copyFileToDirectory(File srcFile, File org.testifyproject.testifyprojectstDir, boolean preserveFileDate) throws IOException { if (org.testifyproject.testifyprojectstDir == null) { throw new NullPointerException("Destination must not be null"); } if (org.testifyproject.testifyprojectstDir.exists() && org.testifyproject.testifyprojectstDir.isDirectory() == false) { throw new IllegalArgumentException("Destination '" + org.testifyproject.testifyprojectstDir + "' is not a directory"); } File org.testifyproject.testifyprojectstFile = new File(org.testifyproject.testifyprojectstDir, srcFile.getName()); copyFile(srcFile, org.testifyproject.testifyprojectstFile, preserveFileDate); } /** * Copies a file to a new location preserving the file date. *

* This method copies the contents of the specified source file to the * specified org.testifyproject.testifyprojectstination file. The directory holding the org.testifyproject.testifyprojectstination file is * created if it does not exist. If the org.testifyproject.testifyprojectstination file exists, then this * method will overwrite it. *

* Note: This method tries to preserve the file's last * modified date/times using {@link File#setLastModified(long)}, however * it is not guaranteed that the operation will succeed. * If the modification operation fails, no indication is provided. * * @param srcFile an existing file to copy, must not be {@code null} * @param org.testifyproject.testifyprojectstFile the new file, must not be {@code null} * * @throws NullPointerException if source or org.testifyproject.testifyprojectstination is {@code null} * @throws IOException if source or org.testifyproject.testifyprojectstination is invalid * @throws IOException if an IO error occurs during copying * @see #copyFileToDirectory(File, File) */ public static void copyFile(File srcFile, File org.testifyproject.testifyprojectstFile) throws IOException { copyFile(srcFile, org.testifyproject.testifyprojectstFile, true); } /** * Copies a file to a new location. *

* This method copies the contents of the specified source file * to the specified org.testifyproject.testifyprojectstination file. * The directory holding the org.testifyproject.testifyprojectstination file is created if it does not exist. * If the org.testifyproject.testifyprojectstination file exists, then this method will overwrite it. *

* Note: Setting preserveFileDate to * {@code true} tries to preserve the file's last modified * date/times using {@link File#setLastModified(long)}, however it is * not guaranteed that the operation will succeed. * If the modification operation fails, no indication is provided. * * @param srcFile an existing file to copy, must not be {@code null} * @param org.testifyproject.testifyprojectstFile the new file, must not be {@code null} * @param preserveFileDate true if the file date of the copy * should be the same as the original * * @throws NullPointerException if source or org.testifyproject.testifyprojectstination is {@code null} * @throws IOException if source or org.testifyproject.testifyprojectstination is invalid * @throws IOException if an IO error occurs during copying * @see #copyFileToDirectory(File, File, boolean) */ public static void copyFile(File srcFile, File org.testifyproject.testifyprojectstFile, boolean preserveFileDate) throws IOException { if (srcFile == null) { throw new NullPointerException("Source must not be null"); } if (org.testifyproject.testifyprojectstFile == null) { throw new NullPointerException("Destination must not be null"); } if (srcFile.exists() == false) { throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); } if (srcFile.isDirectory()) { throw new IOException("Source '" + srcFile + "' exists but is a directory"); } if (srcFile.getCanonicalPath().equals(org.testifyproject.testifyprojectstFile.getCanonicalPath())) { throw new IOException("Source '" + srcFile + "' and org.testifyproject.testifyprojectstination '" + org.testifyproject.testifyprojectstFile + "' are the same"); } File parentFile = org.testifyproject.testifyprojectstFile.getParentFile(); if (parentFile != null) { if (!parentFile.mkdirs() && !parentFile.isDirectory()) { throw new IOException("Destination '" + parentFile + "' directory cannot be created"); } } if (org.testifyproject.testifyprojectstFile.exists() && org.testifyproject.testifyprojectstFile.canWrite() == false) { throw new IOException("Destination '" + org.testifyproject.testifyprojectstFile + "' exists but is read-only"); } doCopyFile(srcFile, org.testifyproject.testifyprojectstFile, preserveFileDate); } /** * Copy bytes from a File to an OutputStream. *

* This method buffers the input internally, so there is no need to use a BufferedInputStream. *

* * @param input * the File to read from * @param output * the OutputStream to write to * @return the number of bytes copied * @throws NullPointerException * if the input or output is null * @throws IOException * if an I/O error occurs * @since 2.1 */ public static long copyFile(File input, OutputStream output) throws IOException { final FileInputStream fis = new FileInputStream(input); try { return IOUtils.copyLarge(fis, output); } finally { fis.close(); } } /** * Internal copy file method. * * @param srcFile the validated source file, must not be {@code null} * @param org.testifyproject.testifyprojectstFile the validated org.testifyproject.testifyprojectstination file, must not be {@code null} * @param preserveFileDate whether to preserve the file date * @throws IOException if an error occurs */ private static void doCopyFile(File srcFile, File org.testifyproject.testifyprojectstFile, boolean preserveFileDate) throws IOException { if (org.testifyproject.testifyprojectstFile.exists() && org.testifyproject.testifyprojectstFile.isDirectory()) { throw new IOException("Destination '" + org.testifyproject.testifyprojectstFile + "' exists but is a directory"); } FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(org.testifyproject.testifyprojectstFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size) { count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos; pos += output.transferFrom(input, pos, count); } } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(input); IOUtils.closeQuietly(fis); } if (srcFile.length() != org.testifyproject.testifyprojectstFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + org.testifyproject.testifyprojectstFile + "'"); } if (preserveFileDate) { org.testifyproject.testifyprojectstFile.setLastModified(srcFile.lastModified()); } } //----------------------------------------------------------------------- /** * Copies a directory to within another directory preserving the file dates. *

* This method copies the source directory and all its contents to a * directory of the same name in the specified org.testifyproject.testifyprojectstination directory. *

* The org.testifyproject.testifyprojectstination directory is created if it does not exist. * If the org.testifyproject.testifyprojectstination directory did exist, then this method merges * the source with the org.testifyproject.testifyprojectstination, with the source taking precedence. *

* Note: This method tries to preserve the files' last * modified date/times using {@link File#setLastModified(long)}, however * it is not guaranteed that those operations will succeed. * If the modification operation fails, no indication is provided. * * @param srcDir an existing directory to copy, must not be {@code null} * @param org.testifyproject.testifyprojectstDir the directory to place the copy in, must not be {@code null} * * @throws NullPointerException if source or org.testifyproject.testifyprojectstination is {@code null} * @throws IOException if source or org.testifyproject.testifyprojectstination is invalid * @throws IOException if an IO error occurs during copying * @since 1.2 */ public static void copyDirectoryToDirectory(File srcDir, File org.testifyproject.testifyprojectstDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (srcDir.exists() && srcDir.isDirectory() == false) { throw new IllegalArgumentException("Source '" + org.testifyproject.testifyprojectstDir + "' is not a directory"); } if (org.testifyproject.testifyprojectstDir == null) { throw new NullPointerException("Destination must not be null"); } if (org.testifyproject.testifyprojectstDir.exists() && org.testifyproject.testifyprojectstDir.isDirectory() == false) { throw new IllegalArgumentException("Destination '" + org.testifyproject.testifyprojectstDir + "' is not a directory"); } copyDirectory(srcDir, new File(org.testifyproject.testifyprojectstDir, srcDir.getName()), true); } /** * Copies a whole directory to a new location preserving the file dates. *

* This method copies the specified directory and all its child * directories and files to the specified org.testifyproject.testifyprojectstination. * The org.testifyproject.testifyprojectstination is the new location and name of the directory. *

* The org.testifyproject.testifyprojectstination directory is created if it does not exist. * If the org.testifyproject.testifyprojectstination directory did exist, then this method merges * the source with the org.testifyproject.testifyprojectstination, with the source taking precedence. *

* Note: This method tries to preserve the files' last * modified date/times using {@link File#setLastModified(long)}, however * it is not guaranteed that those operations will succeed. * If the modification operation fails, no indication is provided. * * @param srcDir an existing directory to copy, must not be {@code null} * @param org.testifyproject.testifyprojectstDir the new directory, must not be {@code null} * * @throws NullPointerException if source or org.testifyproject.testifyprojectstination is {@code null} * @throws IOException if source or org.testifyproject.testifyprojectstination is invalid * @throws IOException if an IO error occurs during copying * @since 1.1 */ public static void copyDirectory(File srcDir, File org.testifyproject.testifyprojectstDir) throws IOException { copyDirectory(srcDir, org.testifyproject.testifyprojectstDir, true); } /** * Copies a whole directory to a new location. *

* This method copies the contents of the specified source directory * to within the specified org.testifyproject.testifyprojectstination directory. *

* The org.testifyproject.testifyprojectstination directory is created if it does not exist. * If the org.testifyproject.testifyprojectstination directory did exist, then this method merges * the source with the org.testifyproject.testifyprojectstination, with the source taking precedence. *

* Note: Setting preserveFileDate to * {@code true} tries to preserve the files' last modified * date/times using {@link File#setLastModified(long)}, however it is * not guaranteed that those operations will succeed. * If the modification operation fails, no indication is provided. * * @param srcDir an existing directory to copy, must not be {@code null} * @param org.testifyproject.testifyprojectstDir the new directory, must not be {@code null} * @param preserveFileDate true if the file date of the copy * should be the same as the original * * @throws NullPointerException if source or org.testifyproject.testifyprojectstination is {@code null} * @throws IOException if source or org.testifyproject.testifyprojectstination is invalid * @throws IOException if an IO error occurs during copying * @since 1.1 */ public static void copyDirectory(File srcDir, File org.testifyproject.testifyprojectstDir, boolean preserveFileDate) throws IOException { copyDirectory(srcDir, org.testifyproject.testifyprojectstDir, null, preserveFileDate); } /** * Copies a filtered directory to a new location preserving the file dates. *

* This method copies the contents of the specified source directory * to within the specified org.testifyproject.testifyprojectstination directory. *

* The org.testifyproject.testifyprojectstination directory is created if it does not exist. * If the org.testifyproject.testifyprojectstination directory did exist, then this method merges * the source with the org.testifyproject.testifyprojectstination, with the source taking precedence. *

* Note: This method tries to preserve the files' last * modified date/times using {@link File#setLastModified(long)}, however * it is not guaranteed that those operations will succeed. * If the modification operation fails, no indication is provided. * *

Example: Copy directories only

*
     *  // only copy the directory structure
     *  FileUtils.copyDirectory(srcDir, org.testifyproject.testifyprojectstDir, DirectoryFileFilter.DIRECTORY);
     *  
* *

Example: Copy directories and txt files

*
     *  // Create a filter for ".txt" files
     *  IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt");
     *  IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter);
     *
     *  // Create a filter for either directories or ".txt" files
     *  FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles);
     *
     *  // Copy using the filter
     *  FileUtils.copyDirectory(srcDir, org.testifyproject.testifyprojectstDir, filter);
     *  
* * @param srcDir an existing directory to copy, must not be {@code null} * @param org.testifyproject.testifyprojectstDir the new directory, must not be {@code null} * @param filter the filter to apply, null means copy all directories and files * should be the same as the original * * @throws NullPointerException if source or org.testifyproject.testifyprojectstination is {@code null} * @throws IOException if source or org.testifyproject.testifyprojectstination is invalid * @throws IOException if an IO error occurs during copying * @since 1.4 */ public static void copyDirectory(File srcDir, File org.testifyproject.testifyprojectstDir, FileFilter filter) throws IOException { copyDirectory(srcDir, org.testifyproject.testifyprojectstDir, filter, true); } /** * Copies a filtered directory to a new location. *

* This method copies the contents of the specified source directory * to within the specified org.testifyproject.testifyprojectstination directory. *

* The org.testifyproject.testifyprojectstination directory is created if it does not exist. * If the org.testifyproject.testifyprojectstination directory did exist, then this method merges * the source with the org.testifyproject.testifyprojectstination, with the source taking precedence. *

* Note: Setting preserveFileDate to * {@code true} tries to preserve the files' last modified * date/times using {@link File#setLastModified(long)}, however it is * not guaranteed that those operations will succeed. * If the modification operation fails, no indication is provided. * *

Example: Copy directories only

*
     *  // only copy the directory structure
     *  FileUtils.copyDirectory(srcDir, org.testifyproject.testifyprojectstDir, DirectoryFileFilter.DIRECTORY, false);
     *  
* *

Example: Copy directories and txt files

*
     *  // Create a filter for ".txt" files
     *  IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt");
     *  IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter);
     *
     *  // Create a filter for either directories or ".txt" files
     *  FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles);
     *
     *  // Copy using the filter
     *  FileUtils.copyDirectory(srcDir, org.testifyproject.testifyprojectstDir, filter, false);
     *  
* * @param srcDir an existing directory to copy, must not be {@code null} * @param org.testifyproject.testifyprojectstDir the new directory, must not be {@code null} * @param filter the filter to apply, null means copy all directories and files * @param preserveFileDate true if the file date of the copy * should be the same as the original * * @throws NullPointerException if source or org.testifyproject.testifyprojectstination is {@code null} * @throws IOException if source or org.testifyproject.testifyprojectstination is invalid * @throws IOException if an IO error occurs during copying * @since 1.4 */ public static void copyDirectory(File srcDir, File org.testifyproject.testifyprojectstDir, FileFilter filter, boolean preserveFileDate) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (org.testifyproject.testifyprojectstDir == null) { throw new NullPointerException("Destination must not be null"); } if (srcDir.exists() == false) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (srcDir.isDirectory() == false) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(org.testifyproject.testifyprojectstDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and org.testifyproject.testifyprojectstination '" + org.testifyproject.testifyprojectstDir + "' are the same"); } // Cater for org.testifyproject.testifyprojectstination being directory within the source directory (see IO-141) List exclusionList = null; if (org.testifyproject.testifyprojectstDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList(srcFiles.length); for (File srcFile : srcFiles) { File copiedFile = new File(org.testifyproject.testifyprojectstDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, org.testifyproject.testifyprojectstDir, filter, preserveFileDate, exclusionList); } /** * Internal copy directory method. * * @param srcDir the validated source directory, must not be {@code null} * @param org.testifyproject.testifyprojectstDir the validated org.testifyproject.testifyprojectstination directory, must not be {@code null} * @param filter the filter to apply, null means copy all directories and files * @param preserveFileDate whether to preserve the file date * @param exclusionList List of files and directories to exclude from the copy, may be null * @throws IOException if an error occurs * @since 1.1 */ private static void doCopyDirectory(File srcDir, File org.testifyproject.testifyprojectstDir, FileFilter filter, boolean preserveFileDate, List exclusionList) throws IOException { // recurse File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter); if (srcFiles == null) { // null if abstract pathname does not org.testifyproject.testifyprojectnote a directory, or if an I/O error occurs throw new IOException("Failed to list contents of " + srcDir); } if (org.testifyproject.testifyprojectstDir.exists()) { if (org.testifyproject.testifyprojectstDir.isDirectory() == false) { throw new IOException("Destination '" + org.testifyproject.testifyprojectstDir + "' exists but is not a directory"); } } else { if (!org.testifyproject.testifyprojectstDir.mkdirs() && !org.testifyproject.testifyprojectstDir.isDirectory()) { throw new IOException("Destination '" + org.testifyproject.testifyprojectstDir + "' directory cannot be created"); } } if (org.testifyproject.testifyprojectstDir.canWrite() == false) { throw new IOException("Destination '" + org.testifyproject.testifyprojectstDir + "' cannot be written to"); } for (File srcFile : srcFiles) { File dstFile = new File(org.testifyproject.testifyprojectstDir, srcFile.getName()); if (exclusionList == null || !exclusionList.contains(srcFile.getCanonicalPath())) { if (srcFile.isDirectory()) { doCopyDirectory(srcFile, dstFile, filter, preserveFileDate, exclusionList); } else { doCopyFile(srcFile, dstFile, preserveFileDate); } } } // Do this last, as the above has probably affected directory metadata if (preserveFileDate) { org.testifyproject.testifyprojectstDir.setLastModified(srcDir.lastModified()); } } //----------------------------------------------------------------------- /** * Copies bytes from the URL source to a file * org.testifyproject.testifyprojectstination. The directories up to org.testifyproject.testifyprojectstination * will be created if they don't already exist. org.testifyproject.testifyprojectstination * will be overwritten if it already exists. *

* Warning: this method does not set a connection or read timeout and thus * might block forever. Use {@link #copyURLToFile(URL, File, int, int)} * with reasonable timeouts to prevent this. * * @param source the URL to copy bytes from, must not be {@code null} * @param org.testifyproject.testifyprojectstination the non-directory File to write bytes to * (possibly overwriting), must not be {@code null} * @throws IOException if source URL cannot be opened * @throws IOException if org.testifyproject.testifyprojectstination is a directory * @throws IOException if org.testifyproject.testifyprojectstination cannot be written * @throws IOException if org.testifyproject.testifyprojectstination needs creating but can't be * @throws IOException if an IO error occurs during copying */ public static void copyURLToFile(URL source, File org.testifyproject.testifyprojectstination) throws IOException { InputStream input = source.openStream(); copyInputStreamToFile(input, org.testifyproject.testifyprojectstination); } /** * Copies bytes from the URL source to a file * org.testifyproject.testifyprojectstination. The directories up to org.testifyproject.testifyprojectstination * will be created if they don't already exist. org.testifyproject.testifyprojectstination * will be overwritten if it already exists. * * @param source the URL to copy bytes from, must not be {@code null} * @param org.testifyproject.testifyprojectstination the non-directory File to write bytes to * (possibly overwriting), must not be {@code null} * @param connectionTimeout the number of milliseconds until this method * will timeout if no connection could be established to the source * @param readTimeout the number of milliseconds until this method will * timeout if no data could be read from the source * @throws IOException if source URL cannot be opened * @throws IOException if org.testifyproject.testifyprojectstination is a directory * @throws IOException if org.testifyproject.testifyprojectstination cannot be written * @throws IOException if org.testifyproject.testifyprojectstination needs creating but can't be * @throws IOException if an IO error occurs during copying * @since 2.0 */ public static void copyURLToFile(URL source, File org.testifyproject.testifyprojectstination, int connectionTimeout, int readTimeout) throws IOException { URLConnection connection = source.openConnection(); connection.setConnectTimeout(connectionTimeout); connection.setReadTimeout(readTimeout); InputStream input = connection.getInputStream(); copyInputStreamToFile(input, org.testifyproject.testifyprojectstination); } /** * Copies bytes from an {@link InputStream} source to a file * org.testifyproject.testifyprojectstination. The directories up to org.testifyproject.testifyprojectstination * will be created if they don't already exist. org.testifyproject.testifyprojectstination * will be overwritten if it already exists. * * @param source the InputStream to copy bytes from, must not be {@code null} * @param org.testifyproject.testifyprojectstination the non-directory File to write bytes to * (possibly overwriting), must not be {@code null} * @throws IOException if org.testifyproject.testifyprojectstination is a directory * @throws IOException if org.testifyproject.testifyprojectstination cannot be written * @throws IOException if org.testifyproject.testifyprojectstination needs creating but can't be * @throws IOException if an IO error occurs during copying * @since 2.0 */ public static void copyInputStreamToFile(InputStream source, File org.testifyproject.testifyprojectstination) throws IOException { try { FileOutputStream output = openOutputStream(org.testifyproject.testifyprojectstination); try { IOUtils.copy(source, output); output.close(); // don't swallow close Exception if copy org.testifyproject.testifyprojectpletes normally } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(source); } } //----------------------------------------------------------------------- /** * Deletes a directory recursively. * * @param directory directory to org.testifyproject.testifyprojectlete * @throws IOException in case org.testifyproject.testifyprojectletion is unsuccessful */ public static void org.testifyproject.testifyprojectleteDirectory(File directory) throws IOException { if (!directory.exists()) { return; } if (!isSymlink(directory)) { cleanDirectory(directory); } if (!directory.org.testifyproject.testifyprojectlete()) { String message = "Unable to org.testifyproject.testifyprojectlete directory " + directory + "."; throw new IOException(message); } } /** * Deletes a file, never throwing an exception. If file is a directory, org.testifyproject.testifyprojectlete it and all sub-directories. *

* The difference between File.org.testifyproject.testifyprojectlete() and this method are: *

    *
  • A directory to be org.testifyproject.testifyprojectleted does not have to be empty.
  • *
  • No exceptions are thrown when a file or directory cannot be org.testifyproject.testifyprojectleted.
  • *
* * @param file file or directory to org.testifyproject.testifyprojectlete, can be {@code null} * @return {@code true} if the file or directory was org.testifyproject.testifyprojectleted, otherwise * {@code false} * * @since 1.4 */ public static boolean org.testifyproject.testifyprojectleteQuietly(File file) { if (file == null) { return false; } try { if (file.isDirectory()) { cleanDirectory(file); } } catch (Exception ignored) { } try { return file.org.testifyproject.testifyprojectlete(); } catch (Exception ignored) { return false; } } /** * Determines whether the {@code parent} directory contains the {@code child} element (a file or directory). *

* Files are normalized before org.testifyproject.testifyprojectparison. *

* * Edge cases: *
    *
  • A {@code directory} must not be null: if null, throw IllegalArgumentException
  • *
  • A {@code directory} must be a directory: if not a directory, throw IllegalArgumentException
  • *
  • A directory does not contain itself: return false
  • *
  • A null child file is not contained in any parent: return false
  • *
* * @param directory * the file to consider as the parent. * @param child * the file to consider as the child. * @return true is the candidate leaf is under by the specified org.testifyproject.testifyprojectposite. False otherwise. * @throws IOException * if an IO error occurs while checking the files. * @since 2.2 * @see FilenameUtils#directoryContains(String, String) */ public static boolean directoryContains(final File directory, final File child) throws IOException { // Fail fast against NullPointerException if (directory == null) { throw new IllegalArgumentException("Directory must not be null"); } if (!directory.isDirectory()) { throw new IllegalArgumentException("Not a directory: " + directory); } if (child == null) { return false; } if (!directory.exists() || !child.exists()) { return false; } // Canonicalize paths (normalizes relative paths) String canonicalParent = directory.getCanonicalPath(); String canonicalChild = child.getCanonicalPath(); return FilenameUtils.directoryContains(canonicalParent, canonicalChild); } /** * Cleans a directory without org.testifyproject.testifyprojectleting it. * * @param directory directory to clean * @throws IOException in case cleaning is unsuccessful */ public static void cleanDirectory(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (File file : files) { try { forceDelete(file); } catch (IOException org.testifyproject.testifyprojecte) { exception = org.testifyproject.testifyprojecte; } } if (null != exception) { throw exception; } } //----------------------------------------------------------------------- /** * Waits for NFS to propagate a file creation, imposing a timeout. *

* This method repeatedly tests {@link File#exists()} until it returns * true up to the maximum time specified in seconds. * * @param file the file to check, must not be {@code null} * @param seconds the maximum time in seconds to wait * @return true if file exists * @throws NullPointerException if the file is {@code null} */ public static boolean waitFor(File file, int seconds) { int timeout = 0; int tick = 0; while (!file.exists()) { if (tick++ >= 10) { tick = 0; if (timeout++ > seconds) { return false; } } try { Thread.sleep(100); } catch (InterruptedException ignore) { // ignore exception } catch (Exception ex) { break; } } return true; } //----------------------------------------------------------------------- /** * Reads the contents of a file into a String. * The file is always closed. * * @param file the file to read, must not be {@code null} * @param encoding the encoding to use, {@code null} means platform org.testifyproject.testifyprojectfault * @return the file contents, never {@code null} * @throws IOException in case of an I/O error * @since 2.3 */ public static String readFileToString(File file, Charset encoding) throws IOException { InputStream in = null; try { in = openInputStream(file); return IOUtils.toString(in, Charsets.toCharset(encoding)); } finally { IOUtils.closeQuietly(in); } } /** * Reads the contents of a file into a String. The file is always closed. * * @param file * the file to read, must not be {@code null} * @param encoding * the encoding to use, {@code null} means platform org.testifyproject.testifyprojectfault * @return the file contents, never {@code null} * @throws IOException * in case of an I/O error * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 2.3 */ public static String readFileToString(File file, String encoding) throws IOException { return readFileToString(file, Charsets.toCharset(encoding)); } /** * Reads the contents of a file into a String using the org.testifyproject.testifyprojectfault encoding for the VM. * The file is always closed. * * @param file the file to read, must not be {@code null} * @return the file contents, never {@code null} * @throws IOException in case of an I/O error * @since 1.3.1 */ public static String readFileToString(File file) throws IOException { return readFileToString(file, Charset.org.testifyproject.testifyprojectfaultCharset()); } /** * Reads the contents of a file into a byte array. * The file is always closed. * * @param file the file to read, must not be {@code null} * @return the file contents, never {@code null} * @throws IOException in case of an I/O error * @since 1.1 */ public static byte[] readFileToByteArray(File file) throws IOException { InputStream in = null; try { in = openInputStream(file); return IOUtils.toByteArray(in, file.length()); } finally { IOUtils.closeQuietly(in); } } /** * Reads the contents of a file line by line to a List of Strings. * The file is always closed. * * @param file the file to read, must not be {@code null} * @param encoding the encoding to use, {@code null} means platform org.testifyproject.testifyprojectfault * @return the list of Strings representing each line in the file, never {@code null} * @throws IOException in case of an I/O error * @since 2.3 */ public static List readLines(File file, Charset encoding) throws IOException { InputStream in = null; try { in = openInputStream(file); return IOUtils.readLines(in, Charsets.toCharset(encoding)); } finally { IOUtils.closeQuietly(in); } } /** * Reads the contents of a file line by line to a List of Strings. The file is always closed. * * @param file * the file to read, must not be {@code null} * @param encoding * the encoding to use, {@code null} means platform org.testifyproject.testifyprojectfault * @return the list of Strings representing each line in the file, never {@code null} * @throws IOException * in case of an I/O error * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 1.1 */ public static List readLines(File file, String encoding) throws IOException { return readLines(file, Charsets.toCharset(encoding)); } /** * Reads the contents of a file line by line to a List of Strings using the org.testifyproject.testifyprojectfault encoding for the VM. * The file is always closed. * * @param file the file to read, must not be {@code null} * @return the list of Strings representing each line in the file, never {@code null} * @throws IOException in case of an I/O error * @since 1.3 */ public static List readLines(File file) throws IOException { return readLines(file, Charset.org.testifyproject.testifyprojectfaultCharset()); } /** * Returns an Iterator for the lines in a File. *

* This method opens an InputStream for the file. * When you have finished with the iterator you should close the stream * to free internal resources. This can be done by calling the * {@link LineIterator#close()} or * {@link LineIterator#closeQuietly(LineIterator)} method. *

* The recommended usage pattern is: *

     * LineIterator it = FileUtils.lineIterator(file, "UTF-8");
     * try {
     *   while (it.hasNext()) {
     *     String line = it.nextLine();
     *     /// do something with line
     *   }
     * } finally {
     *   LineIterator.closeQuietly(iterator);
     * }
     * 
*

* If an exception occurs during the creation of the iterator, the * underlying stream is closed. * * @param file the file to open for input, must not be {@code null} * @param encoding the encoding to use, {@code null} means platform org.testifyproject.testifyprojectfault * @return an Iterator of the lines in the file, never {@code null} * @throws IOException in case of an I/O error (file closed) * @since 1.2 */ public static LineIterator lineIterator(File file, String encoding) throws IOException { InputStream in = null; try { in = openInputStream(file); return IOUtils.lineIterator(in, encoding); } catch (IOException ex) { IOUtils.closeQuietly(in); throw ex; } catch (RuntimeException ex) { IOUtils.closeQuietly(in); throw ex; } } /** * Returns an Iterator for the lines in a File using the org.testifyproject.testifyprojectfault encoding for the VM. * * @param file the file to open for input, must not be {@code null} * @return an Iterator of the lines in the file, never {@code null} * @throws IOException in case of an I/O error (file closed) * @since 1.3 * @see #lineIterator(File, String) */ public static LineIterator lineIterator(File file) throws IOException { return lineIterator(file, null); } //----------------------------------------------------------------------- /** * Writes a String to a file creating the file if it does not exist. * * NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * * @param file the file to write * @param data the content to write to the file * @param encoding the encoding to use, {@code null} means platform org.testifyproject.testifyprojectfault * @throws IOException in case of an I/O error * @throws java.org.testifyproject.testifyproject.UnsupportedEncodingException if the encoding is not supported by the VM */ public static void writeStringToFile(File file, String data, String encoding) throws IOException { writeStringToFile(file, data, encoding, false); } /** * Writes a String to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param encoding the encoding to use, {@code null} means platform org.testifyproject.testifyprojectfault * @param append if {@code true}, then the String will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.3 */ public static void writeStringToFile(File file, String data, Charset encoding, boolean append) throws IOException { OutputStream out = null; try { out = openOutputStream(file, append); IOUtils.write(data, out, encoding); out.close(); // don't swallow close Exception if copy org.testifyproject.testifyprojectpletes normally } finally { IOUtils.closeQuietly(out); } } /** * Writes a String to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param encoding the encoding to use, {@code null} means platform org.testifyproject.testifyprojectfault * @param append if {@code true}, then the String will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported by the VM * @since 2.1 */ public static void writeStringToFile(File file, String data, String encoding, boolean append) throws IOException { writeStringToFile(file, data, Charsets.toCharset(encoding), append); } /** * Writes a String to a file creating the file if it does not exist using the org.testifyproject.testifyprojectfault encoding for the VM. * * @param file the file to write * @param data the content to write to the file * @throws IOException in case of an I/O error */ public static void writeStringToFile(File file, String data) throws IOException { writeStringToFile(file, data, Charset.org.testifyproject.testifyprojectfaultCharset(), false); } /** * Writes a String to a file creating the file if it does not exist using the org.testifyproject.testifyprojectfault encoding for the VM. * * @param file the file to write * @param data the content to write to the file * @param append if {@code true}, then the String will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 */ public static void writeStringToFile(File file, String data, boolean append) throws IOException { writeStringToFile(file, data, Charset.org.testifyproject.testifyprojectfaultCharset(), append); } /** * Writes a CharSequence to a file creating the file if it does not exist using the org.testifyproject.testifyprojectfault encoding for the VM. * * @param file the file to write * @param data the content to write to the file * @throws IOException in case of an I/O error * @since 2.0 */ public static void write(File file, CharSequence data) throws IOException { write(file, data, Charset.org.testifyproject.testifyprojectfaultCharset(), false); } /** * Writes a CharSequence to a file creating the file if it does not exist using the org.testifyproject.testifyprojectfault encoding for the VM. * * @param file the file to write * @param data the content to write to the file * @param append if {@code true}, then the data will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 */ public static void write(File file, CharSequence data, boolean append) throws IOException { write(file, data, Charset.org.testifyproject.testifyprojectfaultCharset(), append); } /** * Writes a CharSequence to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param encoding the encoding to use, {@code null} means platform org.testifyproject.testifyprojectfault * @throws IOException in case of an I/O error * @since 2.3 */ public static void write(File file, CharSequence data, Charset encoding) throws IOException { write(file, data, encoding, false); } /** * Writes a CharSequence to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param encoding the encoding to use, {@code null} means platform org.testifyproject.testifyprojectfault * @throws IOException in case of an I/O error * @throws java.org.testifyproject.testifyproject.UnsupportedEncodingException if the encoding is not supported by the VM * @since 2.0 */ public static void write(File file, CharSequence data, String encoding) throws IOException { write(file, data, encoding, false); } /** * Writes a CharSequence to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param encoding the encoding to use, {@code null} means platform org.testifyproject.testifyprojectfault * @param append if {@code true}, then the data will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since IO 2.3 */ public static void write(File file, CharSequence data, Charset encoding, boolean append) throws IOException { String str = data == null ? null : data.toString(); writeStringToFile(file, str, encoding, append); } /** * Writes a CharSequence to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param encoding the encoding to use, {@code null} means platform org.testifyproject.testifyprojectfault * @param append if {@code true}, then the data will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported by the VM * @since IO 2.1 */ public static void write(File file, CharSequence data, String encoding, boolean append) throws IOException { write(file, data, Charsets.toCharset(encoding), append); } /** * Writes a byte array to a file creating the file if it does not exist. *

* NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * * @param file the file to write to * @param data the content to write to the file * @throws IOException in case of an I/O error * @since 1.1 */ public static void writeByteArrayToFile(File file, byte[] data) throws IOException { writeByteArrayToFile(file, data, false); } /** * Writes a byte array to a file creating the file if it does not exist. * * @param file the file to write to * @param data the content to write to the file * @param append if {@code true}, then bytes will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since IO 2.1 */ public static void writeByteArrayToFile(File file, byte[] data, boolean append) throws IOException { OutputStream out = null; try { out = openOutputStream(file, append); out.write(data); out.close(); // don't swallow close Exception if copy org.testifyproject.testifyprojectpletes normally } finally { IOUtils.closeQuietly(out); } } /** * Writes the toString() value of each item in a collection to * the specified File line by line. * The specified character encoding and the org.testifyproject.testifyprojectfault line ending will be used. *

* NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * * @param file the file to write to * @param encoding the encoding to use, {@code null} means platform org.testifyproject.testifyprojectfault * @param lines the lines to write, {@code null} entries produce blank lines * @throws IOException in case of an I/O error * @throws java.org.testifyproject.testifyproject.UnsupportedEncodingException if the encoding is not supported by the VM * @since 1.1 */ public static void writeLines(File file, String encoding, Collection lines) throws IOException { writeLines(file, encoding, lines, null, false); } /** * Writes the toString() value of each item in a collection to * the specified File line by line, optionally appending. * The specified character encoding and the org.testifyproject.testifyprojectfault line ending will be used. * * @param file the file to write to * @param encoding the encoding to use, {@code null} means platform org.testifyproject.testifyprojectfault * @param lines the lines to write, {@code null} entries produce blank lines * @param append if {@code true}, then the lines will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @throws java.org.testifyproject.testifyproject.UnsupportedEncodingException if the encoding is not supported by the VM * @since 2.1 */ public static void writeLines(File file, String encoding, Collection lines, boolean append) throws IOException { writeLines(file, encoding, lines, null, append); } /** * Writes the toString() value of each item in a collection to * the specified File line by line. * The org.testifyproject.testifyprojectfault VM encoding and the org.testifyproject.testifyprojectfault line ending will be used. * * @param file the file to write to * @param lines the lines to write, {@code null} entries produce blank lines * @throws IOException in case of an I/O error * @since 1.3 */ public static void writeLines(File file, Collection lines) throws IOException { writeLines(file, null, lines, null, false); } /** * Writes the toString() value of each item in a collection to * the specified File line by line. * The org.testifyproject.testifyprojectfault VM encoding and the org.testifyproject.testifyprojectfault line ending will be used. * * @param file the file to write to * @param lines the lines to write, {@code null} entries produce blank lines * @param append if {@code true}, then the lines will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 */ public static void writeLines(File file, Collection lines, boolean append) throws IOException { writeLines(file, null, lines, null, append); } /** * Writes the toString() value of each item in a collection to * the specified File line by line. * The specified character encoding and the line ending will be used. *

* NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * * @param file the file to write to * @param encoding the encoding to use, {@code null} means platform org.testifyproject.testifyprojectfault * @param lines the lines to write, {@code null} entries produce blank lines * @param lineEnding the line separator to use, {@code null} is system org.testifyproject.testifyprojectfault * @throws IOException in case of an I/O error * @throws java.org.testifyproject.testifyproject.UnsupportedEncodingException if the encoding is not supported by the VM * @since 1.1 */ public static void writeLines(File file, String encoding, Collection lines, String lineEnding) throws IOException { writeLines(file, encoding, lines, lineEnding, false); } /** * Writes the toString() value of each item in a collection to * the specified File line by line. * The specified character encoding and the line ending will be used. * * @param file the file to write to * @param encoding the encoding to use, {@code null} means platform org.testifyproject.testifyprojectfault * @param lines the lines to write, {@code null} entries produce blank lines * @param lineEnding the line separator to use, {@code null} is system org.testifyproject.testifyprojectfault * @param append if {@code true}, then the lines will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @throws java.org.testifyproject.testifyproject.UnsupportedEncodingException if the encoding is not supported by the VM * @since 2.1 */ public static void writeLines(File file, String encoding, Collection lines, String lineEnding, boolean append) throws IOException { OutputStream out = null; try { out = openOutputStream(file, append); IOUtils.writeLines(lines, lineEnding, out, encoding); out.close(); // don't swallow close Exception if copy org.testifyproject.testifyprojectpletes normally } finally { IOUtils.closeQuietly(out); } } /** * Writes the toString() value of each item in a collection to * the specified File line by line. * The org.testifyproject.testifyprojectfault VM encoding and the specified line ending will be used. * * @param file the file to write to * @param lines the lines to write, {@code null} entries produce blank lines * @param lineEnding the line separator to use, {@code null} is system org.testifyproject.testifyprojectfault * @throws IOException in case of an I/O error * @since 1.3 */ public static void writeLines(File file, Collection lines, String lineEnding) throws IOException { writeLines(file, null, lines, lineEnding, false); } /** * Writes the toString() value of each item in a collection to * the specified File line by line. * The org.testifyproject.testifyprojectfault VM encoding and the specified line ending will be used. * * @param file the file to write to * @param lines the lines to write, {@code null} entries produce blank lines * @param lineEnding the line separator to use, {@code null} is system org.testifyproject.testifyprojectfault * @param append if {@code true}, then the lines will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 */ public static void writeLines(File file, Collection lines, String lineEnding, boolean append) throws IOException { writeLines(file, null, lines, lineEnding, append); } //----------------------------------------------------------------------- /** * Deletes a file. If file is a directory, org.testifyproject.testifyprojectlete it and all sub-directories. *

* The difference between File.org.testifyproject.testifyprojectlete() and this method are: *

    *
  • A directory to be org.testifyproject.testifyprojectleted does not have to be empty.
  • *
  • You get exceptions when a file or directory cannot be org.testifyproject.testifyprojectleted. * (java.org.testifyproject.testifyproject.File methods returns a boolean)
  • *
* * @param file file or directory to org.testifyproject.testifyprojectlete, must not be {@code null} * @throws NullPointerException if the directory is {@code null} * @throws FileNotFoundException if the file was not found * @throws IOException in case org.testifyproject.testifyprojectletion is unsuccessful */ public static void forceDelete(File file) throws IOException { if (file.isDirectory()) { org.testifyproject.testifyprojectleteDirectory(file); } else { boolean filePresent = file.exists(); if (!file.org.testifyproject.testifyprojectlete()) { if (!filePresent){ throw new FileNotFoundException("File does not exist: " + file); } String message = "Unable to org.testifyproject.testifyprojectlete file: " + file; throw new IOException(message); } } } /** * Schedules a file to be org.testifyproject.testifyprojectleted when JVM exits. * If file is directory org.testifyproject.testifyprojectlete it and all sub-directories. * * @param file file or directory to org.testifyproject.testifyprojectlete, must not be {@code null} * @throws NullPointerException if the file is {@code null} * @throws IOException in case org.testifyproject.testifyprojectletion is unsuccessful */ public static void forceDeleteOnExit(File file) throws IOException { if (file.isDirectory()) { org.testifyproject.testifyprojectleteDirectoryOnExit(file); } else { file.org.testifyproject.testifyprojectleteOnExit(); } } /** * Schedules a directory recursively for org.testifyproject.testifyprojectletion on JVM exit. * * @param directory directory to org.testifyproject.testifyprojectlete, must not be {@code null} * @throws NullPointerException if the directory is {@code null} * @throws IOException in case org.testifyproject.testifyprojectletion is unsuccessful */ private static void org.testifyproject.testifyprojectleteDirectoryOnExit(File directory) throws IOException { if (!directory.exists()) { return; } directory.org.testifyproject.testifyprojectleteOnExit(); if (!isSymlink(directory)) { cleanDirectoryOnExit(directory); } } /** * Cleans a directory without org.testifyproject.testifyprojectleting it. * * @param directory directory to clean, must not be {@code null} * @throws NullPointerException if the directory is {@code null} * @throws IOException in case cleaning is unsuccessful */ private static void cleanDirectoryOnExit(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (File file : files) { try { forceDeleteOnExit(file); } catch (IOException org.testifyproject.testifyprojecte) { exception = org.testifyproject.testifyprojecte; } } if (null != exception) { throw exception; } } /** * Makes a directory, including any necessary but nonexistent parent * directories. If a file already exists with specified name but it is * not a directory then an IOException is thrown. * If the directory cannot be created (or does not already exist) * then an IOException is thrown. * * @param directory directory to create, must not be {@code null} * @throws NullPointerException if the directory is {@code null} * @throws IOException if the directory cannot be created or the file already exists but is not a directory */ public static void forceMkdir(File directory) throws IOException { if (directory.exists()) { if (!directory.isDirectory()) { String message = "File " + directory + " exists and is " + "not a directory. Unable to create directory."; throw new IOException(message); } } else { if (!directory.mkdirs()) { // Double-check that some other thread or process hasn't made // the directory in the background if (!directory.isDirectory()) { String message = "Unable to create directory " + directory; throw new IOException(message); } } } } //----------------------------------------------------------------------- /** * Returns the size of the specified file or directory. If the provided * {@link File} is a regular file, then the file's length is returned. * If the argument is a directory, then the size of the directory is * calculated recursively. If a directory or subdirectory is security * restricted, its size will not be included. * * @param file the regular file or directory to return the size * of (must not be {@code null}). * * @return the length of the file, or recursive size of the directory, * provided (in bytes). * * @throws NullPointerException if the file is {@code null} * @throws IllegalArgumentException if the file does not exist. * * @since 2.0 */ public static long sizeOf(File file) { if (!file.exists()) { String message = file + " does not exist"; throw new IllegalArgumentException(message); } if (file.isDirectory()) { return sizeOfDirectory(file); } else { return file.length(); } } /** * Counts the size of a directory recursively (sum of the length of all files). * * @param directory directory to inspect, must not be {@code null} * @return size of directory in bytes, 0 if directory is security restricted * @throws NullPointerException if the directory is {@code null} */ public static long sizeOfDirectory(File directory) { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } long size = 0; File[] files = directory.listFiles(); if (files == null) { // null if security restricted return 0L; } for (File file : files) { size += sizeOf(file); } return size; } //----------------------------------------------------------------------- /** * Tests if the specified File is newer than the reference * File. * * @param file the File of which the modification date must * be org.testifyproject.testifyprojectpared, must not be {@code null} * @param reference the File of which the modification date * is used, must not be {@code null} * @return true if the File exists and has been modified more * recently than the reference File * @throws IllegalArgumentException if the file is {@code null} * @throws IllegalArgumentException if the reference file is {@code null} or doesn't exist */ 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 '" + reference + "' 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 org.testifyproject.testifyprojectpared, must not be {@code null} * @param date the date reference, must not be {@code null} * @return true if the File exists and has been modified * after the given Date. * @throws IllegalArgumentException if the file is {@code null} * @throws IllegalArgumentException if the date is {@code null} */ 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 org.testifyproject.testifyprojectpared, must not be {@code null} * @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. * @throws IllegalArgumentException if the file is {@code null} */ 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; } //----------------------------------------------------------------------- /** * Tests if the specified File is older than the reference * File. * * @param file the File of which the modification date must * be org.testifyproject.testifyprojectpared, must not be {@code null} * @param reference the File of which the modification date * is used, must not be {@code null} * @return true if the File exists and has been modified before * the reference File * @throws IllegalArgumentException if the file is {@code null} * @throws IllegalArgumentException if the reference file is {@code null} or doesn't exist */ public static boolean isFileOlder(File file, File reference) { if (reference == null) { throw new IllegalArgumentException("No specified reference file"); } if (!reference.exists()) { throw new IllegalArgumentException("The reference file '" + reference + "' doesn't exist"); } return isFileOlder(file, reference.lastModified()); } /** * Tests if the specified File is older than the specified * Date. * * @param file the File of which the modification date * must be org.testifyproject.testifyprojectpared, must not be {@code null} * @param date the date reference, must not be {@code null} * @return true if the File exists and has been modified * before the given Date. * @throws IllegalArgumentException if the file is {@code null} * @throws IllegalArgumentException if the date is {@code null} */ public static boolean isFileOlder(File file, Date date) { if (date == null) { throw new IllegalArgumentException("No specified date"); } return isFileOlder(file, date.getTime()); } /** * Tests if the specified File is older than the specified * time reference. * * @param file the File of which the modification date must * be org.testifyproject.testifyprojectpared, must not be {@code null} * @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 before * the given time reference. * @throws IllegalArgumentException if the file is {@code null} */ public static boolean isFileOlder(File file, long timeMillis) { if (file == null) { throw new IllegalArgumentException("No specified file"); } if (!file.exists()) { return false; } return file.lastModified() < timeMillis; } //----------------------------------------------------------------------- /** * Computes the checksum of a file using the CRC32 checksum routine. * The value of the checksum is returned. * * @param file the file to checksum, must not be {@code null} * @return the checksum value * @throws NullPointerException if the file or checksum is {@code null} * @throws IllegalArgumentException if the file is a directory * @throws IOException if an IO error occurs reading the file * @since 1.3 */ public static long checksumCRC32(File file) throws IOException { CRC32 crc = new CRC32(); checksum(file, crc); return crc.getValue(); } /** * Computes the checksum of a file using the specified checksum object. * Multiple files may be checked using one Checksum instance * if org.testifyproject.testifyprojectsired simply by reusing the same checksum object. * For example: *
     *   long csum = FileUtils.checksum(file, new CRC32()).getValue();
     * 
* * @param file the file to checksum, must not be {@code null} * @param checksum the checksum object to be used, must not be {@code null} * @return the checksum specified, updated with the content of the file * @throws NullPointerException if the file or checksum is {@code null} * @throws IllegalArgumentException if the file is a directory * @throws IOException if an IO error occurs reading the file * @since 1.3 */ public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be org.testifyproject.testifyprojectputed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new NullOutputStream()); } finally { IOUtils.closeQuietly(in); } return checksum; } /** * Moves a directory. *

* When the org.testifyproject.testifyprojectstination directory is on another file system, do a "copy and org.testifyproject.testifyprojectlete". * * @param srcDir the directory to be moved * @param org.testifyproject.testifyprojectstDir the org.testifyproject.testifyprojectstination directory * @throws NullPointerException if source or org.testifyproject.testifyprojectstination is {@code null} * @throws FileExistsException if the org.testifyproject.testifyprojectstination directory exists * @throws IOException if source or org.testifyproject.testifyprojectstination is invalid * @throws IOException if an IO error occurs moving the file * @since 1.4 */ public static void moveDirectory(File srcDir, File org.testifyproject.testifyprojectstDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (org.testifyproject.testifyprojectstDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' is not a directory"); } if (org.testifyproject.testifyprojectstDir.exists()) { throw new FileExistsException("Destination '" + org.testifyproject.testifyprojectstDir + "' already exists"); } boolean rename = srcDir.renameTo(org.testifyproject.testifyprojectstDir); if (!rename) { if (org.testifyproject.testifyprojectstDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { throw new IOException("Cannot move directory: "+srcDir+" to a subdirectory of itself: "+org.testifyproject.testifyprojectstDir); } copyDirectory( srcDir, org.testifyproject.testifyprojectstDir ); org.testifyproject.testifyprojectleteDirectory( srcDir ); if (srcDir.exists()) { throw new IOException("Failed to org.testifyproject.testifyprojectlete original directory '" + srcDir + "' after copy to '" + org.testifyproject.testifyprojectstDir + "'"); } } } /** * Moves a directory to another directory. * * @param src the file to be moved * @param org.testifyproject.testifyprojectstDir the org.testifyproject.testifyprojectstination file * @param createDestDir If {@code true} create the org.testifyproject.testifyprojectstination directory, * otherwise if {@code false} throw an IOException * @throws NullPointerException if source or org.testifyproject.testifyprojectstination is {@code null} * @throws FileExistsException if the directory exists in the org.testifyproject.testifyprojectstination directory * @throws IOException if source or org.testifyproject.testifyprojectstination is invalid * @throws IOException if an IO error occurs moving the file * @since 1.4 */ public static void moveDirectoryToDirectory(File src, File org.testifyproject.testifyprojectstDir, boolean createDestDir) throws IOException { if (src == null) { throw new NullPointerException("Source must not be null"); } if (org.testifyproject.testifyprojectstDir == null) { throw new NullPointerException("Destination directory must not be null"); } if (!org.testifyproject.testifyprojectstDir.exists() && createDestDir) { org.testifyproject.testifyprojectstDir.mkdirs(); } if (!org.testifyproject.testifyprojectstDir.exists()) { throw new FileNotFoundException("Destination directory '" + org.testifyproject.testifyprojectstDir + "' does not exist [createDestDir=" + createDestDir +"]"); } if (!org.testifyproject.testifyprojectstDir.isDirectory()) { throw new IOException("Destination '" + org.testifyproject.testifyprojectstDir + "' is not a directory"); } moveDirectory(src, new File(org.testifyproject.testifyprojectstDir, src.getName())); } /** * Moves a file. *

* When the org.testifyproject.testifyprojectstination file is on another file system, do a "copy and org.testifyproject.testifyprojectlete". * * @param srcFile the file to be moved * @param org.testifyproject.testifyprojectstFile the org.testifyproject.testifyprojectstination file * @throws NullPointerException if source or org.testifyproject.testifyprojectstination is {@code null} * @throws FileExistsException if the org.testifyproject.testifyprojectstination file exists * @throws IOException if source or org.testifyproject.testifyprojectstination is invalid * @throws IOException if an IO error occurs moving the file * @since 1.4 */ public static void moveFile(File srcFile, File org.testifyproject.testifyprojectstFile) throws IOException { if (srcFile == null) { throw new NullPointerException("Source must not be null"); } if (org.testifyproject.testifyprojectstFile == null) { throw new NullPointerException("Destination must not be null"); } if (!srcFile.exists()) { throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); } if (srcFile.isDirectory()) { throw new IOException("Source '" + srcFile + "' is a directory"); } if (org.testifyproject.testifyprojectstFile.exists()) { throw new FileExistsException("Destination '" + org.testifyproject.testifyprojectstFile + "' already exists"); } if (org.testifyproject.testifyprojectstFile.isDirectory()) { throw new IOException("Destination '" + org.testifyproject.testifyprojectstFile + "' is a directory"); } boolean rename = srcFile.renameTo(org.testifyproject.testifyprojectstFile); if (!rename) { copyFile( srcFile, org.testifyproject.testifyprojectstFile ); if (!srcFile.org.testifyproject.testifyprojectlete()) { FileUtils.org.testifyproject.testifyprojectleteQuietly(org.testifyproject.testifyprojectstFile); throw new IOException("Failed to org.testifyproject.testifyprojectlete original file '" + srcFile + "' after copy to '" + org.testifyproject.testifyprojectstFile + "'"); } } } /** * Moves a file to a directory. * * @param srcFile the file to be moved * @param org.testifyproject.testifyprojectstDir the org.testifyproject.testifyprojectstination file * @param createDestDir If {@code true} create the org.testifyproject.testifyprojectstination directory, * otherwise if {@code false} throw an IOException * @throws NullPointerException if source or org.testifyproject.testifyprojectstination is {@code null} * @throws FileExistsException if the org.testifyproject.testifyprojectstination file exists * @throws IOException if source or org.testifyproject.testifyprojectstination is invalid * @throws IOException if an IO error occurs moving the file * @since 1.4 */ public static void moveFileToDirectory(File srcFile, File org.testifyproject.testifyprojectstDir, boolean createDestDir) throws IOException { if (srcFile == null) { throw new NullPointerException("Source must not be null"); } if (org.testifyproject.testifyprojectstDir == null) { throw new NullPointerException("Destination directory must not be null"); } if (!org.testifyproject.testifyprojectstDir.exists() && createDestDir) { org.testifyproject.testifyprojectstDir.mkdirs(); } if (!org.testifyproject.testifyprojectstDir.exists()) { throw new FileNotFoundException("Destination directory '" + org.testifyproject.testifyprojectstDir + "' does not exist [createDestDir=" + createDestDir +"]"); } if (!org.testifyproject.testifyprojectstDir.isDirectory()) { throw new IOException("Destination '" + org.testifyproject.testifyprojectstDir + "' is not a directory"); } moveFile(srcFile, new File(org.testifyproject.testifyprojectstDir, srcFile.getName())); } /** * Moves a file or directory to the org.testifyproject.testifyprojectstination directory. *

* When the org.testifyproject.testifyprojectstination is on another file system, do a "copy and org.testifyproject.testifyprojectlete". * * @param src the file or directory to be moved * @param org.testifyproject.testifyprojectstDir the org.testifyproject.testifyprojectstination directory * @param createDestDir If {@code true} create the org.testifyproject.testifyprojectstination directory, * otherwise if {@code false} throw an IOException * @throws NullPointerException if source or org.testifyproject.testifyprojectstination is {@code null} * @throws FileExistsException if the directory or file exists in the org.testifyproject.testifyprojectstination directory * @throws IOException if source or org.testifyproject.testifyprojectstination is invalid * @throws IOException if an IO error occurs moving the file * @since 1.4 */ public static void moveToDirectory(File src, File org.testifyproject.testifyprojectstDir, boolean createDestDir) throws IOException { if (src == null) { throw new NullPointerException("Source must not be null"); } if (org.testifyproject.testifyprojectstDir == null) { throw new NullPointerException("Destination must not be null"); } if (!src.exists()) { throw new FileNotFoundException("Source '" + src + "' does not exist"); } if (src.isDirectory()) { moveDirectoryToDirectory(src, org.testifyproject.testifyprojectstDir, createDestDir); } else { moveFileToDirectory(src, org.testifyproject.testifyprojectstDir, createDestDir); } } /** * Determines whether the specified file is a Symbolic Link rather than an actual file. *

* Will not return true if there is a Symbolic Link anywhere in the path, * only if the specific file is. *

* Note: the current implementation always returns {@code false} if the system * is org.testifyproject.testifyprojecttected as Windows using {@link FilenameUtils#isSystemWindows()} * * @param file the file to check * @return true if the file is a Symbolic Link * @throws IOException if an IO error occurs while checking the file * @since 2.0 */ public static boolean isSymlink(File file) throws IOException { if (file == null) { throw new NullPointerException("File must not be null"); } if (FilenameUtils.isSystemWindows()) { return false; } File fileInCanonicalDir = null; if (file.getParent() == null) { fileInCanonicalDir = file; } else { File canonicalDir = file.getParentFile().getCanonicalFile(); fileInCanonicalDir = new File(canonicalDir, file.getName()); } if (fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile())) { return false; } else { return true; } } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy