1
0
mirror of https://github.com/moparisthebest/k-9 synced 2024-08-13 17:03:48 -04:00

Replace Apache Commons IO with v2.01 downloaded from apache.org as a

prebuilt JAR
This commit is contained in:
Jesse Vincent 2011-01-31 18:25:26 +00:00
parent d03818079a
commit 2ce5b9ed03
80 changed files with 1 additions and 15781 deletions

View File

@ -5,6 +5,7 @@
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry exported="true" kind="lib" path="libs/apache-mime4j-core-0.7-SNAPSHOT.jar"/>
<classpathentry exported="true" kind="lib" path="libs/apache-mime4j-dom-0.7-SNAPSHOT.jar"/>
<classpathentry kind="lib" path="libs/commons-io-2.0.1.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.USER_LIBRARY/compile-only-libs"/>
<classpathentry kind="output" path="bin"/>
</classpath>

BIN
libs/commons-io-2.0.1.jar Normal file

Binary file not shown.

View File

@ -1,332 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
/**
* This class provides static utility methods for buffered
* copying between sources (<code>InputStream</code>, <code>Reader</code>,
* <code>String</code> and <code>byte[]</code>) and destinations
* (<code>OutputStream</code>, <code>Writer</code>, <code>String</code> and
* <code>byte[]</code>).
* <p>
* Unless otherwise noted, these <code>copy</code> methods do <em>not</em>
* flush or close the streams. Often doing so would require making non-portable
* assumptions about the streams' origin and further use. This means that both
* streams' <code>close()</code> methods must be called after copying. if one
* omits this step, then the stream resources (sockets, file descriptors) are
* released when the associated Stream is garbage-collected. It is not a good
* idea to rely on this mechanism. For a good overview of the distinction
* between "memory management" and "resource management", see
* <a href="http://www.unixreview.com/articles/1998/9804/9804ja/ja.htm">this
* UnixReview article</a>.
* <p>
* For byte-to-char methods, a <code>copy</code> variant allows the encoding
* to be selected (otherwise the platform default is used). We would like to
* encourage you to always specify the encoding because relying on the platform
* default can lead to unexpected results.
* <p
* We don't provide special variants for the <code>copy</code> methods that
* let you specify the buffer size because in modern VMs the impact on speed
* seems to be minimal. We're using a default buffer size of 4 KB.
* <p>
* The <code>copy</code> methods use an internal buffer when copying. It is
* therefore advisable <em>not</em> to deliberately wrap the stream arguments
* to the <code>copy</code> methods in <code>Buffered*</code> streams. For
* example, don't do the following:
* <pre>
* copy( new BufferedInputStream( in ), new BufferedOutputStream( out ) );
* </pre>
* The rationale is as follows:
* <p>
* Imagine that an InputStream's read() is a very expensive operation, which
* would usually suggest wrapping in a BufferedInputStream. The
* BufferedInputStream works by issuing infrequent
* {@link java.io.InputStream#read(byte[] b, int off, int len)} requests on the
* underlying InputStream, to fill an internal buffer, from which further
* <code>read</code> requests can inexpensively get their data (until the buffer
* runs out).
* <p>
* However, the <code>copy</code> methods do the same thing, keeping an
* internal buffer, populated by
* {@link InputStream#read(byte[] b, int off, int len)} requests. Having two
* buffers (or three if the destination stream is also buffered) is pointless,
* and the unnecessary buffer management hurts performance slightly (about 3%,
* according to some simple experiments).
* <p>
* Behold, intrepid explorers; a map of this class:
* <pre>
* Method Input Output Dependency
* ------ ----- ------ -------
* 1 copy InputStream OutputStream (primitive)
* 2 copy Reader Writer (primitive)
*
* 3 copy InputStream Writer 2
*
* 4 copy Reader OutputStream 2
*
* 5 copy String OutputStream 2
* 6 copy String Writer (trivial)
*
* 7 copy byte[] Writer 3
* 8 copy byte[] OutputStream (trivial)
* </pre>
* <p>
* Note that only the first two methods shuffle bytes; the rest use these
* two, or (if possible) copy using native Java copy methods. As there are
* method variants to specify the encoding, each row may
* correspond to up to 2 methods.
* <p>
* Origin of code: Excalibur.
*
* @author Peter Donald
* @author Jeff Turner
* @author Matthew Hawthorne
* @version $Id: CopyUtils.java 437680 2006-08-28 11:57:00Z scolebourne $
* @deprecated Use IOUtils. Will be removed in 2.0.
* Methods renamed to IOUtils.write() or IOUtils.copy().
* Null handling behaviour changed in IOUtils (null data does not
* throw NullPointerException).
*/
public class CopyUtils {
/**
* The default size of the buffer.
*/
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
/**
* Instances should NOT be constructed in standard programming.
*/
public CopyUtils() { }
// ----------------------------------------------------------------
// byte[] -> OutputStream
// ----------------------------------------------------------------
/**
* Copy bytes from a <code>byte[]</code> to an <code>OutputStream</code>.
* @param input the byte array to read from
* @param output the <code>OutputStream</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(byte[] input, OutputStream output)
throws IOException {
output.write(input);
}
// ----------------------------------------------------------------
// byte[] -> Writer
// ----------------------------------------------------------------
/**
* Copy and convert bytes from a <code>byte[]</code> to chars on a
* <code>Writer</code>.
* The platform's default encoding is used for the byte-to-char conversion.
* @param input the byte array to read from
* @param output the <code>Writer</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(byte[] input, Writer output)
throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(input);
copy(in, output);
}
/**
* Copy and convert bytes from a <code>byte[]</code> to chars on a
* <code>Writer</code>, using the specified encoding.
* @param input the byte array to read from
* @param output the <code>Writer</code> to write to
* @param encoding The name of a supported character encoding. See the
* <a href="http://www.iana.org/assignments/character-sets">IANA
* Charset Registry</a> for a list of valid encoding types.
* @throws IOException In case of an I/O problem
*/
public static void copy(
byte[] input,
Writer output,
String encoding)
throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(input);
copy(in, output, encoding);
}
// ----------------------------------------------------------------
// Core copy methods
// ----------------------------------------------------------------
/**
* Copy bytes from an <code>InputStream</code> to an
* <code>OutputStream</code>.
* @param input the <code>InputStream</code> to read from
* @param output the <code>OutputStream</code> to write to
* @return the number of bytes copied
* @throws IOException In case of an I/O problem
*/
public static int copy(
InputStream input,
OutputStream output)
throws IOException {
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
// ----------------------------------------------------------------
// Reader -> Writer
// ----------------------------------------------------------------
/**
* Copy chars from a <code>Reader</code> to a <code>Writer</code>.
* @param input the <code>Reader</code> to read from
* @param output the <code>Writer</code> to write to
* @return the number of characters copied
* @throws IOException In case of an I/O problem
*/
public static int copy(
Reader input,
Writer output)
throws IOException {
char[] buffer = new char[DEFAULT_BUFFER_SIZE];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
// ----------------------------------------------------------------
// InputStream -> Writer
// ----------------------------------------------------------------
/**
* Copy and convert bytes from an <code>InputStream</code> to chars on a
* <code>Writer</code>.
* The platform's default encoding is used for the byte-to-char conversion.
* @param input the <code>InputStream</code> to read from
* @param output the <code>Writer</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(
InputStream input,
Writer output)
throws IOException {
InputStreamReader in = new InputStreamReader(input);
copy(in, output);
}
/**
* Copy and convert bytes from an <code>InputStream</code> to chars on a
* <code>Writer</code>, using the specified encoding.
* @param input the <code>InputStream</code> to read from
* @param output the <code>Writer</code> to write to
* @param encoding The name of a supported character encoding. See the
* <a href="http://www.iana.org/assignments/character-sets">IANA
* Charset Registry</a> for a list of valid encoding types.
* @throws IOException In case of an I/O problem
*/
public static void copy(
InputStream input,
Writer output,
String encoding)
throws IOException {
InputStreamReader in = new InputStreamReader(input, encoding);
copy(in, output);
}
// ----------------------------------------------------------------
// Reader -> OutputStream
// ----------------------------------------------------------------
/**
* Serialize chars from a <code>Reader</code> to bytes on an
* <code>OutputStream</code>, and flush the <code>OutputStream</code>.
* @param input the <code>Reader</code> to read from
* @param output the <code>OutputStream</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(
Reader input,
OutputStream output)
throws IOException {
OutputStreamWriter out = new OutputStreamWriter(output);
copy(input, out);
// XXX Unless anyone is planning on rewriting OutputStreamWriter, we
// have to flush here.
out.flush();
}
// ----------------------------------------------------------------
// String -> OutputStream
// ----------------------------------------------------------------
/**
* Serialize chars from a <code>String</code> to bytes on an
* <code>OutputStream</code>, and
* flush the <code>OutputStream</code>.
* @param input the <code>String</code> to read from
* @param output the <code>OutputStream</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(
String input,
OutputStream output)
throws IOException {
StringReader in = new StringReader(input);
OutputStreamWriter out = new OutputStreamWriter(output);
copy(in, out);
// XXX Unless anyone is planning on rewriting OutputStreamWriter, we
// have to flush here.
out.flush();
}
// ----------------------------------------------------------------
// String -> Writer
// ----------------------------------------------------------------
/**
* Copy chars from a <code>String</code> to a <code>Writer</code>.
* @param input the <code>String</code> to read from
* @param output the <code>Writer</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(String input, Writer output)
throws IOException {
output.write(input);
}
}

View File

@ -1,620 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Collection;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
/**
* Abstract class that walks through a directory hierarchy and provides
* subclasses with convenient hooks to add specific behaviour.
* <p>
* This class operates with a {@link FileFilter} and maximum depth to
* limit the files and direcories visited.
* Commons IO supplies many common filter implementations in the
* <a href="filefilter/package-summary.html"> filefilter</a> package.
* <p>
* The following sections describe:
* <ul>
* <li><a href="#example">1. Example Implementation</a> - example
* <code>FileCleaner</code> implementation.</li>
* <li><a href="#filter">2. Filter Example</a> - using
* {@link FileFilter}(s) with <code>DirectoryWalker</code>.</li>
* <li><a href="#cancel">3. Cancellation</a> - how to implement cancellation
* behaviour.</li>
* </ul>
*
* <a name="example"></a>
* <h3>1. Example Implementation</h3>
*
* There are many possible extensions, for example, to delete all
* files and '.svn' directories, and return a list of deleted files:
* <pre>
* public class FileCleaner extends DirectoryWalker {
*
* public FileCleaner() {
* super();
* }
*
* public List clean(File startDirectory) {
* List results = new ArrayList();
* walk(startDirectory, results);
* return results;
* }
*
* protected boolean handleDirectory(File directory, int depth, Collection results) {
* // delete svn directories and then skip
* if (".svn".equals(directory.getName())) {
* directory.delete();
* return false;
* } else {
* return true;
* }
*
* }
*
* protected void handleFile(File file, int depth, Collection results) {
* // delete file and add to list of deleted
* file.delete();
* results.add(file);
* }
* }
* </pre>
*
* <a name="filter"></a>
* <h3>2. Filter Example</h3>
*
* Choosing which directories and files to process can be a key aspect
* of using this class. This information can be setup in three ways,
* via three different constructors.
* <p>
* The first option is to visit all directories and files.
* This is achieved via the no-args constructor.
* <p>
* The second constructor option is to supply a single {@link FileFilter}
* that describes the files and directories to visit. Care must be taken
* with this option as the same filter is used for both directories
* and files.
* <p>
* For example, if you wanted all directories which are not hidden
* and files which end in ".txt":
* <pre>
* public class FooDirectoryWalker extends DirectoryWalker {
* public FooDirectoryWalker(FileFilter filter) {
* super(filter, -1);
* }
* }
*
* // Build up the filters and create the walker
* // Create a filter for Non-hidden directories
* IOFileFilter fooDirFilter =
* FileFilterUtils.andFileFilter(FileFilterUtils.directoryFileFilter,
* HiddenFileFilter.VISIBLE);
*
* // Create a filter for Files ending in ".txt"
* IOFileFilter fooFileFilter =
* FileFilterUtils.andFileFilter(FileFilterUtils.fileFileFilter,
* FileFilterUtils.suffixFileFilter(".txt"));
*
* // Combine the directory and file filters using an OR condition
* java.io.FileFilter fooFilter =
* FileFilterUtils.orFileFilter(fooDirFilter, fooFileFilter);
*
* // Use the filter to construct a DirectoryWalker implementation
* FooDirectoryWalker walker = new FooDirectoryWalker(fooFilter);
* </pre>
* <p>
* The third constructor option is to specify separate filters, one for
* directories and one for files. These are combined internally to form
* the correct <code>FileFilter</code>, something which is very easy to
* get wrong when attempted manually, particularly when trying to
* express constructs like 'any file in directories named docs'.
* <p>
* For example, if you wanted all directories which are not hidden
* and files which end in ".txt":
* <pre>
* public class FooDirectoryWalker extends DirectoryWalker {
* public FooDirectoryWalker(IOFileFilter dirFilter, IOFileFilter fileFilter) {
* super(dirFilter, fileFilter, -1);
* }
* }
*
* // Use the filters to construct the walker
* FooDirectoryWalker walker = new FooDirectoryWalker(
* HiddenFileFilter.VISIBLE,
* FileFilterUtils.suffixFileFilter(".txt"),
* );
* </pre>
* This is much simpler than the previous example, and is why it is the preferred
* option for filtering.
*
* <a name="cancel"></a>
* <h3>3. Cancellation</h3>
*
* The DirectoryWalker contains some of the logic required for cancel processing.
* Subclasses must complete the implementation.
* <p>
* What <code>DirectoryWalker</code> does provide for cancellation is:
* <ul>
* <li>{@link CancelException} which can be thrown in any of the
* <i>lifecycle</i> methods to stop processing.</li>
* <li>The <code>walk()</code> method traps thrown {@link CancelException}
* and calls the <code>handleCancelled()</code> method, providing
* a place for custom cancel processing.</li>
* </ul>
* <p>
* Implementations need to provide:
* <ul>
* <li>The decision logic on whether to cancel processing or not.</li>
* <li>Constructing and throwing a {@link CancelException}.</li>
* <li>Custom cancel processing in the <code>handleCancelled()</code> method.
* </ul>
* <p>
* Two possible scenarios are envisaged for cancellation:
* <ul>
* <li><a href="#external">3.1 External / Mult-threaded</a> - cancellation being
* decided/initiated by an external process.</li>
* <li><a href="#internal">3.2 Internal</a> - cancellation being decided/initiated
* from within a DirectoryWalker implementation.</li>
* </ul>
* <p>
* The following sections provide example implementations for these two different
* scenarios.
*
* <a name="external"></a>
* <h4>3.1 External / Multi-threaded</h4>
*
* This example provides a public <code>cancel()</code> method that can be
* called by another thread to stop the processing. A typical example use-case
* would be a cancel button on a GUI. Calling this method sets a
* <a href="http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#36930">
* volatile</a> flag to ensure it will work properly in a multi-threaded environment.
* The flag is returned by the <code>handleIsCancelled()</code> method, which
* will cause the walk to stop immediately. The <code>handleCancelled()</code>
* method will be the next, and last, callback method received once cancellation
* has occurred.
*
* <pre>
* public class FooDirectoryWalker extends DirectoryWalker {
*
* private volatile boolean cancelled = false;
*
* public void cancel() {
* cancelled = true;
* }
*
* private void handleIsCancelled(File file, int depth, Collection results) {
* return cancelled;
* }
*
* protected void handleCancelled(File startDirectory, Collection results, CancelException cancel) {
* // implement processing required when a cancellation occurs
* }
* }
* </pre>
*
* <a name="internal"></a>
* <h4>3.2 Internal</h4>
*
* This shows an example of how internal cancellation processing could be implemented.
* <b>Note</b> the decision logic and throwing a {@link CancelException} could be implemented
* in any of the <i>lifecycle</i> methods.
*
* <pre>
* public class BarDirectoryWalker extends DirectoryWalker {
*
* protected boolean handleDirectory(File directory, int depth, Collection results) throws IOException {
* // cancel if hidden directory
* if (directory.isHidden()) {
* throw new CancelException(file, depth);
* }
* return true;
* }
*
* protected void handleFile(File file, int depth, Collection results) throws IOException {
* // cancel if read-only file
* if (!file.canWrite()) {
* throw new CancelException(file, depth);
* }
* results.add(file);
* }
*
* protected void handleCancelled(File startDirectory, Collection results, CancelException cancel) {
* // implement processing required when a cancellation occurs
* }
* }
* </pre>
*
* @since Commons IO 1.3
* @version $Revision: 424748 $
*/
public abstract class DirectoryWalker {
/**
* The file filter to use to filter files and directories.
*/
private final FileFilter filter;
/**
* The limit on the directory depth to walk.
*/
private final int depthLimit;
/**
* Construct an instance with no filtering and unlimited <i>depth</i>.
*/
protected DirectoryWalker() {
this(null, -1);
}
/**
* Construct an instance with a filter and limit the <i>depth</i> navigated to.
* <p>
* The filter controls which files and directories will be navigated to as
* part of the walk. The {@link FileFilterUtils} class is useful for combining
* various filters together. A <code>null</code> filter means that no
* filtering should occur and all files and directories will be visited.
*
* @param filter the filter to apply, null means visit all files
* @param depthLimit controls how <i>deep</i> the hierarchy is
* navigated to (less than 0 means unlimited)
*/
protected DirectoryWalker(FileFilter filter, int depthLimit) {
this.filter = filter;
this.depthLimit = depthLimit;
}
/**
* Construct an instance with a directory and a file filter and an optional
* limit on the <i>depth</i> navigated to.
* <p>
* The filters control which files and directories will be navigated to as part
* of the walk. This constructor uses {@link FileFilterUtils#makeDirectoryOnly(IOFileFilter)}
* and {@link FileFilterUtils#makeFileOnly(IOFileFilter)} internally to combine the filters.
* A <code>null</code> filter means that no filtering should occur.
*
* @param directoryFilter the filter to apply to directories, null means visit all directories
* @param fileFilter the filter to apply to files, null means visit all files
* @param depthLimit controls how <i>deep</i> the hierarchy is
* navigated to (less than 0 means unlimited)
*/
protected DirectoryWalker(IOFileFilter directoryFilter, IOFileFilter fileFilter, int depthLimit) {
if (directoryFilter == null && fileFilter == null) {
this.filter = null;
} else {
directoryFilter = (directoryFilter != null ? directoryFilter : TrueFileFilter.TRUE);
fileFilter = (fileFilter != null ? fileFilter : TrueFileFilter.TRUE);
directoryFilter = FileFilterUtils.makeDirectoryOnly(directoryFilter);
fileFilter = FileFilterUtils.makeFileOnly(fileFilter);
this.filter = FileFilterUtils.orFileFilter(directoryFilter, fileFilter);
}
this.depthLimit = depthLimit;
}
//-----------------------------------------------------------------------
/**
* Internal method that walks the directory hierarchy in a depth-first manner.
* <p>
* Users of this class do not need to call this method. This method will
* be called automatically by another (public) method on the specific subclass.
* <p>
* Writers of subclasses should call this method to start the directory walk.
* Once called, this method will emit events as it walks the hierarchy.
* The event methods have the prefix <code>handle</code>.
*
* @param startDirectory the directory to start from, not null
* @param results the collection of result objects, may be updated
* @throws NullPointerException if the start directory is null
* @throws IOException if an I/O Error occurs
*/
protected final void walk(File startDirectory, Collection results) throws IOException {
if (startDirectory == null) {
throw new NullPointerException("Start Directory is null");
}
try {
handleStart(startDirectory, results);
walk(startDirectory, 0, results);
handleEnd(results);
} catch(CancelException cancel) {
handleCancelled(startDirectory, results, cancel);
}
}
/**
* Main recursive method to examine the directory hierarchy.
*
* @param directory the directory to examine, not null
* @param depth the directory level (starting directory = 0)
* @param results the collection of result objects, may be updated
* @throws IOException if an I/O Error occurs
*/
private void walk(File directory, int depth, Collection results) throws IOException {
checkIfCancelled(directory, depth, results);
if (handleDirectory(directory, depth, results)) {
handleDirectoryStart(directory, depth, results);
int childDepth = depth + 1;
if (depthLimit < 0 || childDepth <= depthLimit) {
checkIfCancelled(directory, depth, results);
File[] childFiles = (filter == null ? directory.listFiles() : directory.listFiles(filter));
if (childFiles == null) {
handleRestricted(directory, childDepth, results);
} else {
for (int i = 0; i < childFiles.length; i++) {
File childFile = childFiles[i];
if (childFile.isDirectory()) {
walk(childFile, childDepth, results);
} else {
checkIfCancelled(childFile, childDepth, results);
handleFile(childFile, childDepth, results);
checkIfCancelled(childFile, childDepth, results);
}
}
}
}
handleDirectoryEnd(directory, depth, results);
}
checkIfCancelled(directory, depth, results);
}
//-----------------------------------------------------------------------
/**
* Checks whether the walk has been cancelled by calling {@link #handleIsCancelled},
* throwing a <code>CancelException</code> if it has.
* <p>
* Writers of subclasses should not normally call this method as it is called
* automatically by the walk of the tree. However, sometimes a single method,
* typically {@link #handleFile}, may take a long time to run. In that case,
* you may wish to check for cancellation by calling this method.
*
* @param file the current file being processed
* @param depth the current file level (starting directory = 0)
* @param results the collection of result objects, may be updated
* @throws IOException if an I/O Error occurs
*/
protected final void checkIfCancelled(File file, int depth, Collection results) throws IOException {
if (handleIsCancelled(file, depth, results)) {
throw new CancelException(file, depth);
}
}
/**
* Overridable callback method invoked to determine if the entire walk
* operation should be immediately cancelled.
* <p>
* This method should be implemented by those subclasses that want to
* provide a public <code>cancel()</code> method available from another
* thread. The design pattern for the subclass should be as follows:
* <pre>
* public class FooDirectoryWalker extends DirectoryWalker {
* private volatile boolean cancelled = false;
*
* public void cancel() {
* cancelled = true;
* }
* private void handleIsCancelled(File file, int depth, Collection results) {
* return cancelled;
* }
* protected void handleCancelled(File startDirectory,
* Collection results, CancelException cancel) {
* // implement processing required when a cancellation occurs
* }
* }
* </pre>
* <p>
* If this method returns true, then the directory walk is immediately
* cancelled. The next callback method will be {@link #handleCancelled}.
* <p>
* This implementation returns false.
*
* @param file the file or directory being processed
* @param depth the current directory level (starting directory = 0)
* @param results the collection of result objects, may be updated
* @return true if the walk has been cancelled
* @throws IOException if an I/O Error occurs
*/
protected boolean handleIsCancelled(
File file, int depth, Collection results) throws IOException {
// do nothing - overridable by subclass
return false; // not cancelled
}
/**
* Overridable callback method invoked when the operation is cancelled.
* The file being processed when the cancellation occurred can be
* obtained from the exception.
* <p>
* This implementation just re-throws the {@link CancelException}.
*
* @param startDirectory the directory that the walk started from
* @param results the collection of result objects, may be updated
* @param cancel the exception throw to cancel further processing
* containing details at the point of cancellation.
* @throws IOException if an I/O Error occurs
*/
protected void handleCancelled(File startDirectory, Collection results,
CancelException cancel) throws IOException {
// re-throw exception - overridable by subclass
throw cancel;
}
//-----------------------------------------------------------------------
/**
* Overridable callback method invoked at the start of processing.
* <p>
* This implementation does nothing.
*
* @param startDirectory the directory to start from
* @param results the collection of result objects, may be updated
* @throws IOException if an I/O Error occurs
*/
protected void handleStart(File startDirectory, Collection results) throws IOException {
// do nothing - overridable by subclass
}
/**
* Overridable callback method invoked to determine if a directory should be processed.
* <p>
* This method returns a boolean to indicate if the directory should be examined or not.
* If you return false, the entire directory and any subdirectories will be skipped.
* Note that this functionality is in addition to the filtering by file filter.
* <p>
* This implementation does nothing and returns true.
*
* @param directory the current directory being processed
* @param depth the current directory level (starting directory = 0)
* @param results the collection of result objects, may be updated
* @return true to process this directory, false to skip this directory
* @throws IOException if an I/O Error occurs
*/
protected boolean handleDirectory(File directory, int depth, Collection results) throws IOException {
// do nothing - overridable by subclass
return true; // process directory
}
/**
* Overridable callback method invoked at the start of processing each directory.
* <p>
* This implementation does nothing.
*
* @param directory the current directory being processed
* @param depth the current directory level (starting directory = 0)
* @param results the collection of result objects, may be updated
* @throws IOException if an I/O Error occurs
*/
protected void handleDirectoryStart(File directory, int depth, Collection results) throws IOException {
// do nothing - overridable by subclass
}
/**
* Overridable callback method invoked for each (non-directory) file.
* <p>
* This implementation does nothing.
*
* @param file the current file being processed
* @param depth the current directory level (starting directory = 0)
* @param results the collection of result objects, may be updated
* @throws IOException if an I/O Error occurs
*/
protected void handleFile(File file, int depth, Collection results) throws IOException {
// do nothing - overridable by subclass
}
/**
* Overridable callback method invoked for each restricted directory.
* <p>
* This implementation does nothing.
*
* @param directory the restricted directory
* @param depth the current directory level (starting directory = 0)
* @param results the collection of result objects, may be updated
* @throws IOException if an I/O Error occurs
*/
protected void handleRestricted(File directory, int depth, Collection results) throws IOException {
// do nothing - overridable by subclass
}
/**
* Overridable callback method invoked at the end of processing each directory.
* <p>
* This implementation does nothing.
*
* @param directory the directory being processed
* @param depth the current directory level (starting directory = 0)
* @param results the collection of result objects, may be updated
* @throws IOException if an I/O Error occurs
*/
protected void handleDirectoryEnd(File directory, int depth, Collection results) throws IOException {
// do nothing - overridable by subclass
}
/**
* Overridable callback method invoked at the end of processing.
* <p>
* This implementation does nothing.
*
* @param results the collection of result objects, may be updated
* @throws IOException if an I/O Error occurs
*/
protected void handleEnd(Collection results) throws IOException {
// do nothing - overridable by subclass
}
//-----------------------------------------------------------------------
/**
* CancelException is thrown in DirectoryWalker to cancel the current
* processing.
*/
public static class CancelException extends IOException {
/** Serialization id. */
private static final long serialVersionUID = 1347339620135041008L;
/** The file being processed when the exception was thrown. */
private File file;
/** The file depth when the exception was thrown. */
private int depth = -1;
/**
* Constructs a <code>CancelException</code> with
* the file and depth when cancellation occurred.
*
* @param file the file when the operation was cancelled, may be null
* @param depth the depth when the operation was cancelled, may be null
*/
public CancelException(File file, int depth) {
this("Operation Cancelled", file, depth);
}
/**
* Constructs a <code>CancelException</code> with
* an appropriate message and the file and depth when
* cancellation occurred.
*
* @param message the detail message
* @param file the file when the operation was cancelled
* @param depth the depth when the operation was cancelled
*/
public CancelException(String message, File file, int depth) {
super(message);
this.file = file;
this.depth = depth;
}
/**
* Return the file when the operation was cancelled.
*
* @return the file when the operation was cancelled
*/
public File getFile() {
return file;
}
/**
* Return the depth when the operation was cancelled.
*
* @return the depth when the operation was cancelled
*/
public int getDepth() {
return depth;
}
}
}

View File

@ -1,489 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Utility code for dealing with different endian systems.
* <p>
* Different computer architectures adopt different conventions for
* byte ordering. In so-called "Little Endian" architectures (eg Intel),
* the low-order byte is stored in memory at the lowest address, and
* subsequent bytes at higher addresses. For "Big Endian" architectures
* (eg Motorola), the situation is reversed.
* This class helps you solve this incompatability.
* <p>
* Origin of code: Excalibur
*
* @author <a href="mailto:peter@apache.org">Peter Donald</a>
* @version $Id: EndianUtils.java 539632 2007-05-18 23:37:59Z bayard $
* @see org.apache.commons.io.input.SwappedDataInputStream
*/
public class EndianUtils {
/**
* Instances should NOT be constructed in standard programming.
*/
public EndianUtils() {
super();
}
// ========================================== Swapping routines
/**
* Converts a "short" value between endian systems.
* @param value value to convert
* @return the converted value
*/
public static short swapShort(short value) {
return (short) ( ( ( ( value >> 0 ) & 0xff ) << 8 ) +
( ( ( value >> 8 ) & 0xff ) << 0 ) );
}
/**
* Converts a "int" value between endian systems.
* @param value value to convert
* @return the converted value
*/
public static int swapInteger(int value) {
return
( ( ( value >> 0 ) & 0xff ) << 24 ) +
( ( ( value >> 8 ) & 0xff ) << 16 ) +
( ( ( value >> 16 ) & 0xff ) << 8 ) +
( ( ( value >> 24 ) & 0xff ) << 0 );
}
/**
* Converts a "long" value between endian systems.
* @param value value to convert
* @return the converted value
*/
public static long swapLong(long value) {
return
( ( ( value >> 0 ) & 0xff ) << 56 ) +
( ( ( value >> 8 ) & 0xff ) << 48 ) +
( ( ( value >> 16 ) & 0xff ) << 40 ) +
( ( ( value >> 24 ) & 0xff ) << 32 ) +
( ( ( value >> 32 ) & 0xff ) << 24 ) +
( ( ( value >> 40 ) & 0xff ) << 16 ) +
( ( ( value >> 48 ) & 0xff ) << 8 ) +
( ( ( value >> 56 ) & 0xff ) << 0 );
}
/**
* Converts a "float" value between endian systems.
* @param value value to convert
* @return the converted value
*/
public static float swapFloat(float value) {
return Float.intBitsToFloat( swapInteger( Float.floatToIntBits( value ) ) );
}
/**
* Converts a "double" value between endian systems.
* @param value value to convert
* @return the converted value
*/
public static double swapDouble(double value) {
return Double.longBitsToDouble( swapLong( Double.doubleToLongBits( value ) ) );
}
// ========================================== Swapping read/write routines
/**
* Writes a "short" value to a byte array at a given offset. The value is
* converted to the opposed endian system while writing.
* @param data target byte array
* @param offset starting offset in the byte array
* @param value value to write
*/
public static void writeSwappedShort(byte[] data, int offset, short value) {
data[ offset + 0 ] = (byte)( ( value >> 0 ) & 0xff );
data[ offset + 1 ] = (byte)( ( value >> 8 ) & 0xff );
}
/**
* Reads a "short" value from a byte array at a given offset. The value is
* converted to the opposed endian system while reading.
* @param data source byte array
* @param offset starting offset in the byte array
* @return the value read
*/
public static short readSwappedShort(byte[] data, int offset) {
return (short)( ( ( data[ offset + 0 ] & 0xff ) << 0 ) +
( ( data[ offset + 1 ] & 0xff ) << 8 ) );
}
/**
* Reads an unsigned short (16-bit) value from a byte array at a given
* offset. The value is converted to the opposed endian system while
* reading.
* @param data source byte array
* @param offset starting offset in the byte array
* @return the value read
*/
public static int readSwappedUnsignedShort(byte[] data, int offset) {
return ( ( ( data[ offset + 0 ] & 0xff ) << 0 ) +
( ( data[ offset + 1 ] & 0xff ) << 8 ) );
}
/**
* Writes a "int" value to a byte array at a given offset. The value is
* converted to the opposed endian system while writing.
* @param data target byte array
* @param offset starting offset in the byte array
* @param value value to write
*/
public static void writeSwappedInteger(byte[] data, int offset, int value) {
data[ offset + 0 ] = (byte)( ( value >> 0 ) & 0xff );
data[ offset + 1 ] = (byte)( ( value >> 8 ) & 0xff );
data[ offset + 2 ] = (byte)( ( value >> 16 ) & 0xff );
data[ offset + 3 ] = (byte)( ( value >> 24 ) & 0xff );
}
/**
* Reads a "int" value from a byte array at a given offset. The value is
* converted to the opposed endian system while reading.
* @param data source byte array
* @param offset starting offset in the byte array
* @return the value read
*/
public static int readSwappedInteger(byte[] data, int offset) {
return ( ( ( data[ offset + 0 ] & 0xff ) << 0 ) +
( ( data[ offset + 1 ] & 0xff ) << 8 ) +
( ( data[ offset + 2 ] & 0xff ) << 16 ) +
( ( data[ offset + 3 ] & 0xff ) << 24 ) );
}
/**
* Reads an unsigned integer (32-bit) value from a byte array at a given
* offset. The value is converted to the opposed endian system while
* reading.
* @param data source byte array
* @param offset starting offset in the byte array
* @return the value read
*/
public static long readSwappedUnsignedInteger(byte[] data, int offset) {
long low = ( ( ( data[ offset + 0 ] & 0xff ) << 0 ) +
( ( data[ offset + 1 ] & 0xff ) << 8 ) +
( ( data[ offset + 2 ] & 0xff ) << 16 ) );
long high = data[ offset + 3 ] & 0xff;
return (high << 24) + (0xffffffffL & low);
}
/**
* Writes a "long" value to a byte array at a given offset. The value is
* converted to the opposed endian system while writing.
* @param data target byte array
* @param offset starting offset in the byte array
* @param value value to write
*/
public static void writeSwappedLong(byte[] data, int offset, long value) {
data[ offset + 0 ] = (byte)( ( value >> 0 ) & 0xff );
data[ offset + 1 ] = (byte)( ( value >> 8 ) & 0xff );
data[ offset + 2 ] = (byte)( ( value >> 16 ) & 0xff );
data[ offset + 3 ] = (byte)( ( value >> 24 ) & 0xff );
data[ offset + 4 ] = (byte)( ( value >> 32 ) & 0xff );
data[ offset + 5 ] = (byte)( ( value >> 40 ) & 0xff );
data[ offset + 6 ] = (byte)( ( value >> 48 ) & 0xff );
data[ offset + 7 ] = (byte)( ( value >> 56 ) & 0xff );
}
/**
* Reads a "long" value from a byte array at a given offset. The value is
* converted to the opposed endian system while reading.
* @param data source byte array
* @param offset starting offset in the byte array
* @return the value read
*/
public static long readSwappedLong(byte[] data, int offset) {
long low =
( ( data[ offset + 0 ] & 0xff ) << 0 ) +
( ( data[ offset + 1 ] & 0xff ) << 8 ) +
( ( data[ offset + 2 ] & 0xff ) << 16 ) +
( ( data[ offset + 3 ] & 0xff ) << 24 );
long high =
( ( data[ offset + 4 ] & 0xff ) << 0 ) +
( ( data[ offset + 5 ] & 0xff ) << 8 ) +
( ( data[ offset + 6 ] & 0xff ) << 16 ) +
( ( data[ offset + 7 ] & 0xff ) << 24 );
return (high << 32) + (0xffffffffL & low);
}
/**
* Writes a "float" value to a byte array at a given offset. The value is
* converted to the opposed endian system while writing.
* @param data target byte array
* @param offset starting offset in the byte array
* @param value value to write
*/
public static void writeSwappedFloat(byte[] data, int offset, float value) {
writeSwappedInteger( data, offset, Float.floatToIntBits( value ) );
}
/**
* Reads a "float" value from a byte array at a given offset. The value is
* converted to the opposed endian system while reading.
* @param data source byte array
* @param offset starting offset in the byte array
* @return the value read
*/
public static float readSwappedFloat(byte[] data, int offset) {
return Float.intBitsToFloat( readSwappedInteger( data, offset ) );
}
/**
* Writes a "double" value to a byte array at a given offset. The value is
* converted to the opposed endian system while writing.
* @param data target byte array
* @param offset starting offset in the byte array
* @param value value to write
*/
public static void writeSwappedDouble(byte[] data, int offset, double value) {
writeSwappedLong( data, offset, Double.doubleToLongBits( value ) );
}
/**
* Reads a "double" value from a byte array at a given offset. The value is
* converted to the opposed endian system while reading.
* @param data source byte array
* @param offset starting offset in the byte array
* @return the value read
*/
public static double readSwappedDouble(byte[] data, int offset) {
return Double.longBitsToDouble( readSwappedLong( data, offset ) );
}
/**
* Writes a "short" value to an OutputStream. The value is
* converted to the opposed endian system while writing.
* @param output target OutputStream
* @param value value to write
* @throws IOException in case of an I/O problem
*/
public static void writeSwappedShort(OutputStream output, short value)
throws IOException
{
output.write( (byte)( ( value >> 0 ) & 0xff ) );
output.write( (byte)( ( value >> 8 ) & 0xff ) );
}
/**
* Reads a "short" value from an InputStream. The value is
* converted to the opposed endian system while reading.
* @param input source InputStream
* @return the value just read
* @throws IOException in case of an I/O problem
*/
public static short readSwappedShort(InputStream input)
throws IOException
{
return (short)( ( ( read( input ) & 0xff ) << 0 ) +
( ( read( input ) & 0xff ) << 8 ) );
}
/**
* Reads a unsigned short (16-bit) from an InputStream. The value is
* converted to the opposed endian system while reading.
* @param input source InputStream
* @return the value just read
* @throws IOException in case of an I/O problem
*/
public static int readSwappedUnsignedShort(InputStream input)
throws IOException
{
int value1 = read( input );
int value2 = read( input );
return ( ( ( value1 & 0xff ) << 0 ) +
( ( value2 & 0xff ) << 8 ) );
}
/**
* Writes a "int" value to an OutputStream. The value is
* converted to the opposed endian system while writing.
* @param output target OutputStream
* @param value value to write
* @throws IOException in case of an I/O problem
*/
public static void writeSwappedInteger(OutputStream output, int value)
throws IOException
{
output.write( (byte)( ( value >> 0 ) & 0xff ) );
output.write( (byte)( ( value >> 8 ) & 0xff ) );
output.write( (byte)( ( value >> 16 ) & 0xff ) );
output.write( (byte)( ( value >> 24 ) & 0xff ) );
}
/**
* Reads a "int" value from an InputStream. The value is
* converted to the opposed endian system while reading.
* @param input source InputStream
* @return the value just read
* @throws IOException in case of an I/O problem
*/
public static int readSwappedInteger(InputStream input)
throws IOException
{
int value1 = read( input );
int value2 = read( input );
int value3 = read( input );
int value4 = read( input );
return ( ( value1 & 0xff ) << 0 ) +
( ( value2 & 0xff ) << 8 ) +
( ( value3 & 0xff ) << 16 ) +
( ( value4 & 0xff ) << 24 );
}
/**
* Reads a unsigned integer (32-bit) from an InputStream. The value is
* converted to the opposed endian system while reading.
* @param input source InputStream
* @return the value just read
* @throws IOException in case of an I/O problem
*/
public static long readSwappedUnsignedInteger(InputStream input)
throws IOException
{
int value1 = read( input );
int value2 = read( input );
int value3 = read( input );
int value4 = read( input );
long low = ( ( ( value1 & 0xff ) << 0 ) +
( ( value2 & 0xff ) << 8 ) +
( ( value3 & 0xff ) << 16 ) );
long high = value4 & 0xff;
return (high << 24) + (0xffffffffL & low);
}
/**
* Writes a "long" value to an OutputStream. The value is
* converted to the opposed endian system while writing.
* @param output target OutputStream
* @param value value to write
* @throws IOException in case of an I/O problem
*/
public static void writeSwappedLong(OutputStream output, long value)
throws IOException
{
output.write( (byte)( ( value >> 0 ) & 0xff ) );
output.write( (byte)( ( value >> 8 ) & 0xff ) );
output.write( (byte)( ( value >> 16 ) & 0xff ) );
output.write( (byte)( ( value >> 24 ) & 0xff ) );
output.write( (byte)( ( value >> 32 ) & 0xff ) );
output.write( (byte)( ( value >> 40 ) & 0xff ) );
output.write( (byte)( ( value >> 48 ) & 0xff ) );
output.write( (byte)( ( value >> 56 ) & 0xff ) );
}
/**
* Reads a "long" value from an InputStream. The value is
* converted to the opposed endian system while reading.
* @param input source InputStream
* @return the value just read
* @throws IOException in case of an I/O problem
*/
public static long readSwappedLong(InputStream input)
throws IOException
{
byte[] bytes = new byte[8];
for ( int i=0; i<8; i++ ) {
bytes[i] = (byte) read( input );
}
return readSwappedLong( bytes, 0 );
}
/**
* Writes a "float" value to an OutputStream. The value is
* converted to the opposed endian system while writing.
* @param output target OutputStream
* @param value value to write
* @throws IOException in case of an I/O problem
*/
public static void writeSwappedFloat(OutputStream output, float value)
throws IOException
{
writeSwappedInteger( output, Float.floatToIntBits( value ) );
}
/**
* Reads a "float" value from an InputStream. The value is
* converted to the opposed endian system while reading.
* @param input source InputStream
* @return the value just read
* @throws IOException in case of an I/O problem
*/
public static float readSwappedFloat(InputStream input)
throws IOException
{
return Float.intBitsToFloat( readSwappedInteger( input ) );
}
/**
* Writes a "double" value to an OutputStream. The value is
* converted to the opposed endian system while writing.
* @param output target OutputStream
* @param value value to write
* @throws IOException in case of an I/O problem
*/
public static void writeSwappedDouble(OutputStream output, double value)
throws IOException
{
writeSwappedLong( output, Double.doubleToLongBits( value ) );
}
/**
* Reads a "double" value from an InputStream. The value is
* converted to the opposed endian system while reading.
* @param input source InputStream
* @return the value just read
* @throws IOException in case of an I/O problem
*/
public static double readSwappedDouble(InputStream input)
throws IOException
{
return Double.longBitsToDouble( readSwappedLong( input ) );
}
/**
* Reads the next byte from the input stream.
* @param input the stream
* @return the byte
* @throws IOException if the end of file is reached
*/
private static int read(InputStream input)
throws IOException
{
int value = input.read();
if( -1 == value ) {
throw new EOFException( "Unexpected EOF reached" );
}
return value;
}
}

View File

@ -1,154 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io;
import java.io.File;
/**
* Keeps track of files awaiting deletion, and deletes them when an associated
* marker object is reclaimed by the garbage collector.
* <p>
* This utility creates a background thread to handle file deletion.
* Each file to be deleted is registered with a handler object.
* When the handler object is garbage collected, the file is deleted.
* <p>
* In an environment with multiple class loaders (a servlet container, for
* example), you should consider stopping the background thread if it is no
* longer needed. This is done by invoking the method
* {@link #exitWhenFinished}, typically in
* {@link javax.servlet.ServletContextListener#contextDestroyed} or similar.
*
* @author Noel Bergman
* @author Martin Cooper
* @version $Id: FileCleaner.java 553012 2007-07-03 23:01:07Z ggregory $
* @deprecated Use {@link FileCleaningTracker}
*/
public class FileCleaner {
/**
* The instance to use for the deprecated, static methods.
*/
static final FileCleaningTracker theInstance = new FileCleaningTracker();
//-----------------------------------------------------------------------
/**
* Track the specified file, using the provided marker, deleting the file
* when the marker instance is garbage collected.
* The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used.
*
* @param file the file to be tracked, not null
* @param marker the marker object used to track the file, not null
* @throws NullPointerException if the file is null
* @deprecated Use {@link FileCleaningTracker#track(File, Object)}.
*/
public static void track(File file, Object marker) {
theInstance.track(file, marker);
}
/**
* Track the specified file, using the provided marker, deleting the file
* when the marker instance is garbage collected.
* The speified deletion strategy is used.
*
* @param file the file to be tracked, not null
* @param marker the marker object used to track the file, not null
* @param deleteStrategy the strategy to delete the file, null means normal
* @throws NullPointerException if the file is null
* @deprecated Use {@link FileCleaningTracker#track(File, Object, FileDeleteStrategy)}.
*/
public static void track(File file, Object marker, FileDeleteStrategy deleteStrategy) {
theInstance.track(file, marker, deleteStrategy);
}
/**
* Track the specified file, using the provided marker, deleting the file
* when the marker instance is garbage collected.
* The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used.
*
* @param path the full path to the file to be tracked, not null
* @param marker the marker object used to track the file, not null
* @throws NullPointerException if the path is null
* @deprecated Use {@link FileCleaningTracker#track(String, Object)}.
*/
public static void track(String path, Object marker) {
theInstance.track(path, marker);
}
/**
* Track the specified file, using the provided marker, deleting the file
* when the marker instance is garbage collected.
* The speified deletion strategy is used.
*
* @param path the full path to the file to be tracked, not null
* @param marker the marker object used to track the file, not null
* @param deleteStrategy the strategy to delete the file, null means normal
* @throws NullPointerException if the path is null
* @deprecated Use {@link FileCleaningTracker#track(String, Object, FileDeleteStrategy)}.
*/
public static void track(String path, Object marker, FileDeleteStrategy deleteStrategy) {
theInstance.track(path, marker, deleteStrategy);
}
//-----------------------------------------------------------------------
/**
* Retrieve the number of files currently being tracked, and therefore
* awaiting deletion.
*
* @return the number of files being tracked
* @deprecated Use {@link FileCleaningTracker#getTrackCount()}.
*/
public static int getTrackCount() {
return theInstance.getTrackCount();
}
/**
* Call this method to cause the file cleaner thread to terminate when
* there are no more objects being tracked for deletion.
* <p>
* In a simple environment, you don't need this method as the file cleaner
* thread will simply exit when the JVM exits. In a more complex environment,
* with multiple class loaders (such as an application server), you should be
* aware that the file cleaner thread will continue running even if the class
* loader it was started from terminates. This can consitute a memory leak.
* <p>
* For example, suppose that you have developed a web application, which
* contains the commons-io jar file in your WEB-INF/lib directory. In other
* words, the FileCleaner class is loaded through the class loader of your
* web application. If the web application is terminated, but the servlet
* container is still running, then the file cleaner thread will still exist,
* posing a memory leak.
* <p>
* This method allows the thread to be terminated. Simply call this method
* in the resource cleanup code, such as {@link javax.servlet.ServletContextListener#contextDestroyed}.
* One called, no new objects can be tracked by the file cleaner.
* @deprecated Use {@link FileCleaningTracker#exitWhenFinished()}.
*/
public static synchronized void exitWhenFinished() {
theInstance.exitWhenFinished();
}
/**
* Returns the singleton instance, which is used by the deprecated, static methods.
* This is mainly useful for code, which wants to support the new
* {@link FileCleaningTracker} class while maintain compatibility with the
* deprecated {@link FileCleaner}.
*
* @return the singleton instance
*/
public static FileCleaningTracker getInstance() {
return theInstance;
}
}

View File

@ -1,258 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io;
import java.io.File;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.Collection;
import java.util.Vector;
/**
* Keeps track of files awaiting deletion, and deletes them when an associated
* marker object is reclaimed by the garbage collector.
* <p>
* This utility creates a background thread to handle file deletion.
* Each file to be deleted is registered with a handler object.
* When the handler object is garbage collected, the file is deleted.
* <p>
* In an environment with multiple class loaders (a servlet container, for
* example), you should consider stopping the background thread if it is no
* longer needed. This is done by invoking the method
* {@link #exitWhenFinished}, typically in
* {@link javax.servlet.ServletContextListener#contextDestroyed} or similar.
*
* @author Noel Bergman
* @author Martin Cooper
* @version $Id: FileCleaner.java 490987 2006-12-29 12:11:48Z scolebourne $
*/
public class FileCleaningTracker {
/**
* Queue of <code>Tracker</code> instances being watched.
*/
ReferenceQueue /* Tracker */ q = new ReferenceQueue();
/**
* Collection of <code>Tracker</code> instances in existence.
*/
final Collection /* Tracker */ trackers = new Vector(); // synchronized
/**
* Whether to terminate the thread when the tracking is complete.
*/
volatile boolean exitWhenFinished = false;
/**
* The thread that will clean up registered files.
*/
Thread reaper;
//-----------------------------------------------------------------------
/**
* Track the specified file, using the provided marker, deleting the file
* when the marker instance is garbage collected.
* The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used.
*
* @param file the file to be tracked, not null
* @param marker the marker object used to track the file, not null
* @throws NullPointerException if the file is null
*/
public void track(File file, Object marker) {
track(file, marker, (FileDeleteStrategy) null);
}
/**
* Track the specified file, using the provided marker, deleting the file
* when the marker instance is garbage collected.
* The speified deletion strategy is used.
*
* @param file the file to be tracked, not null
* @param marker the marker object used to track the file, not null
* @param deleteStrategy the strategy to delete the file, null means normal
* @throws NullPointerException if the file is null
*/
public void track(File file, Object marker, FileDeleteStrategy deleteStrategy) {
if (file == null) {
throw new NullPointerException("The file must not be null");
}
addTracker(file.getPath(), marker, deleteStrategy);
}
/**
* Track the specified file, using the provided marker, deleting the file
* when the marker instance is garbage collected.
* The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used.
*
* @param path the full path to the file to be tracked, not null
* @param marker the marker object used to track the file, not null
* @throws NullPointerException if the path is null
*/
public void track(String path, Object marker) {
track(path, marker, (FileDeleteStrategy) null);
}
/**
* Track the specified file, using the provided marker, deleting the file
* when the marker instance is garbage collected.
* The speified deletion strategy is used.
*
* @param path the full path to the file to be tracked, not null
* @param marker the marker object used to track the file, not null
* @param deleteStrategy the strategy to delete the file, null means normal
* @throws NullPointerException if the path is null
*/
public void track(String path, Object marker, FileDeleteStrategy deleteStrategy) {
if (path == null) {
throw new NullPointerException("The path must not be null");
}
addTracker(path, marker, deleteStrategy);
}
/**
* Adds a tracker to the list of trackers.
*
* @param path the full path to the file to be tracked, not null
* @param marker the marker object used to track the file, not null
* @param deleteStrategy the strategy to delete the file, null means normal
*/
private synchronized void addTracker(String path, Object marker, FileDeleteStrategy deleteStrategy) {
// synchronized block protects reaper
if (exitWhenFinished) {
throw new IllegalStateException("No new trackers can be added once exitWhenFinished() is called");
}
if (reaper == null) {
reaper = new Reaper();
reaper.start();
}
trackers.add(new Tracker(path, deleteStrategy, marker, q));
}
//-----------------------------------------------------------------------
/**
* Retrieve the number of files currently being tracked, and therefore
* awaiting deletion.
*
* @return the number of files being tracked
*/
public int getTrackCount() {
return trackers.size();
}
/**
* Call this method to cause the file cleaner thread to terminate when
* there are no more objects being tracked for deletion.
* <p>
* In a simple environment, you don't need this method as the file cleaner
* thread will simply exit when the JVM exits. In a more complex environment,
* with multiple class loaders (such as an application server), you should be
* aware that the file cleaner thread will continue running even if the class
* loader it was started from terminates. This can consitute a memory leak.
* <p>
* For example, suppose that you have developed a web application, which
* contains the commons-io jar file in your WEB-INF/lib directory. In other
* words, the FileCleaner class is loaded through the class loader of your
* web application. If the web application is terminated, but the servlet
* container is still running, then the file cleaner thread will still exist,
* posing a memory leak.
* <p>
* This method allows the thread to be terminated. Simply call this method
* in the resource cleanup code, such as {@link javax.servlet.ServletContextListener#contextDestroyed}.
* One called, no new objects can be tracked by the file cleaner.
*/
public synchronized void exitWhenFinished() {
// synchronized block protects reaper
exitWhenFinished = true;
if (reaper != null) {
synchronized (reaper) {
reaper.interrupt();
}
}
}
//-----------------------------------------------------------------------
/**
* The reaper thread.
*/
private final class Reaper extends Thread {
/** Construct a new Reaper */
Reaper() {
super("File Reaper");
setPriority(Thread.MAX_PRIORITY);
setDaemon(true);
}
/**
* Run the reaper thread that will delete files as their associated
* marker objects are reclaimed by the garbage collector.
*/
public void run() {
// thread exits when exitWhenFinished is true and there are no more tracked objects
while (exitWhenFinished == false || trackers.size() > 0) {
Tracker tracker = null;
try {
// Wait for a tracker to remove.
tracker = (Tracker) q.remove();
} catch (Exception e) {
continue;
}
if (tracker != null) {
tracker.delete();
tracker.clear();
trackers.remove(tracker);
}
}
}
}
//-----------------------------------------------------------------------
/**
* Inner class which acts as the reference for a file pending deletion.
*/
private static final class Tracker extends PhantomReference {
/**
* The full path to the file being tracked.
*/
private final String path;
/**
* The strategy for deleting files.
*/
private final FileDeleteStrategy deleteStrategy;
/**
* Constructs an instance of this class from the supplied parameters.
*
* @param path the full path to the file to be tracked, not null
* @param deleteStrategy the strategy to delete the file, null means normal
* @param marker the marker object used to track the file, not null
* @param queue the queue on to which the tracker will be pushed, not null
*/
Tracker(String path, FileDeleteStrategy deleteStrategy, Object marker, ReferenceQueue queue) {
super(marker, queue);
this.path = path;
this.deleteStrategy = (deleteStrategy == null ? FileDeleteStrategy.NORMAL : deleteStrategy);
}
/**
* Deletes the file associated with this tracker instance.
*
* @return <code>true</code> if the file was deleted successfully;
* <code>false</code> otherwise.
*/
public boolean delete() {
return deleteStrategy.deleteQuietly(new File(path));
}
}
}

View File

@ -1,156 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io;
import java.io.File;
import java.io.IOException;
/**
* Strategy for deleting files.
* <p>
* There is more than one way to delete a file.
* You may want to limit access to certain directories, to only delete
* directories if they are empty, or maybe to force deletion.
* <p>
* This class captures the strategy to use and is designed for user subclassing.
*
* @author Stephen Colebourne
* @version $Id: FileDeleteStrategy.java 453903 2006-10-07 13:47:06Z scolebourne $
* @since Commons IO 1.3
*/
public class FileDeleteStrategy {
/**
* The singleton instance for normal file deletion, which does not permit
* the deletion of directories that are not empty.
*/
public static final FileDeleteStrategy NORMAL = new FileDeleteStrategy("Normal");
/**
* The singleton instance for forced file deletion, which always deletes,
* even if the file represents a non-empty directory.
*/
public static final FileDeleteStrategy FORCE = new ForceFileDeleteStrategy();
/** The name of the strategy. */
private final String name;
//-----------------------------------------------------------------------
/**
* Restricted constructor.
*
* @param name the name by which the strategy is known
*/
protected FileDeleteStrategy(String name) {
this.name = name;
}
//-----------------------------------------------------------------------
/**
* Deletes the file object, which may be a file or a directory.
* All <code>IOException</code>s are caught and false returned instead.
* If the file does not exist or is null, true is returned.
* <p>
* Subclass writers should override {@link #doDelete(File)}, not this method.
*
* @param fileToDelete the file to delete, null returns true
* @return true if the file was deleted, or there was no such file
*/
public boolean deleteQuietly(File fileToDelete) {
if (fileToDelete == null || fileToDelete.exists() == false) {
return true;
}
try {
return doDelete(fileToDelete);
} catch (IOException ex) {
return false;
}
}
/**
* Deletes the file object, which may be a file or a directory.
* If the file does not exist, the method just returns.
* <p>
* Subclass writers should override {@link #doDelete(File)}, not this method.
*
* @param fileToDelete the file to delete, not null
* @throws NullPointerException if the file is null
* @throws IOException if an error occurs during file deletion
*/
public void delete(File fileToDelete) throws IOException {
if (fileToDelete.exists() && doDelete(fileToDelete) == false) {
throw new IOException("Deletion failed: " + fileToDelete);
}
}
/**
* Actually deletes the file object, which may be a file or a directory.
* <p>
* This method is designed for subclasses to override.
* The implementation may return either false or an <code>IOException</code>
* when deletion fails. The {@link #delete(File)} and {@link #deleteQuietly(File)}
* methods will handle either response appropriately.
* A check has been made to ensure that the file will exist.
* <p>
* This implementation uses {@link File#delete()}.
*
* @param fileToDelete the file to delete, exists, not null
* @return true if the file was deleteds
* @throws NullPointerException if the file is null
* @throws IOException if an error occurs during file deletion
*/
protected boolean doDelete(File fileToDelete) throws IOException {
return fileToDelete.delete();
}
//-----------------------------------------------------------------------
/**
* Gets a string describing the delete strategy.
*
* @return a string describing the delete strategy
*/
public String toString() {
return "FileDeleteStrategy[" + name + "]";
}
//-----------------------------------------------------------------------
/**
* Force file deletion strategy.
*/
static class ForceFileDeleteStrategy extends FileDeleteStrategy {
/** Default Constructor */
ForceFileDeleteStrategy() {
super("Force");
}
/**
* Deletes the file object.
* <p>
* This implementation uses <code>FileUtils.forceDelete() <code>
* if the file exists.
*
* @param fileToDelete the file to delete, not null
* @return Always returns <code>true</code>
* @throws NullPointerException if the file is null
* @throws IOException if an error occurs during file deletion
*/
protected boolean doDelete(File fileToDelete) throws IOException {
FileUtils.forceDelete(fileToDelete);
return true;
}
}
}

View File

@ -1,457 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
/**
* General File System utilities.
* <p>
* This class provides static utility methods for general file system
* functions not provided via the JDK {@link java.io.File File} class.
* <p>
* The current functions provided are:
* <ul>
* <li>Get the free space on a drive
* </ul>
*
* @author Frank W. Zammetti
* @author Stephen Colebourne
* @author Thomas Ledoux
* @author James Urie
* @author Magnus Grimsell
* @author Thomas Ledoux
* @version $Id: FileSystemUtils.java 453889 2006-10-07 11:56:25Z scolebourne $
* @since Commons IO 1.1
*/
public class FileSystemUtils {
/** Singleton instance, used mainly for testing. */
private static final FileSystemUtils INSTANCE = new FileSystemUtils();
/** Operating system state flag for error. */
private static final int INIT_PROBLEM = -1;
/** Operating system state flag for neither Unix nor Windows. */
private static final int OTHER = 0;
/** Operating system state flag for Windows. */
private static final int WINDOWS = 1;
/** Operating system state flag for Unix. */
private static final int UNIX = 2;
/** Operating system state flag for Posix flavour Unix. */
private static final int POSIX_UNIX = 3;
/** The operating system flag. */
private static final int OS;
static {
int os = OTHER;
try {
String osName = System.getProperty("os.name");
if (osName == null) {
throw new IOException("os.name not found");
}
osName = osName.toLowerCase();
// match
if (osName.indexOf("windows") != -1) {
os = WINDOWS;
} else if (osName.indexOf("linux") != -1 ||
osName.indexOf("sun os") != -1 ||
osName.indexOf("sunos") != -1 ||
osName.indexOf("solaris") != -1 ||
osName.indexOf("mpe/ix") != -1 ||
osName.indexOf("freebsd") != -1 ||
osName.indexOf("irix") != -1 ||
osName.indexOf("digital unix") != -1 ||
osName.indexOf("unix") != -1 ||
osName.indexOf("mac os x") != -1) {
os = UNIX;
} else if (osName.indexOf("hp-ux") != -1 ||
osName.indexOf("aix") != -1) {
os = POSIX_UNIX;
} else {
os = OTHER;
}
} catch (Exception ex) {
os = INIT_PROBLEM;
}
OS = os;
}
/**
* Instances should NOT be constructed in standard programming.
*/
public FileSystemUtils() {
super();
}
//-----------------------------------------------------------------------
/**
* Returns the free space on a drive or volume by invoking
* the command line.
* This method does not normalize the result, and typically returns
* bytes on Windows, 512 byte units on OS X and kilobytes on Unix.
* As this is not very useful, this method is deprecated in favour
* of {@link #freeSpaceKb(String)} which returns a result in kilobytes.
* <p>
* Note that some OS's are NOT currently supported, including OS/390,
* OpenVMS and and SunOS 5. (SunOS is supported by <code>freeSpaceKb</code>.)
* <pre>
* FileSystemUtils.freeSpace("C:"); // Windows
* FileSystemUtils.freeSpace("/volume"); // *nix
* </pre>
* The free space is calculated via the command line.
* It uses 'dir /-c' on Windows and 'df' on *nix.
*
* @param path the path to get free space for, not null, not empty on Unix
* @return the amount of free drive space on the drive or volume
* @throws IllegalArgumentException if the path is invalid
* @throws IllegalStateException if an error occurred in initialisation
* @throws IOException if an error occurs when finding the free space
* @since Commons IO 1.1, enhanced OS support in 1.2 and 1.3
* @deprecated Use freeSpaceKb(String)
* Deprecated from 1.3, may be removed in 2.0
*/
public static long freeSpace(String path) throws IOException {
return INSTANCE.freeSpaceOS(path, OS, false);
}
//-----------------------------------------------------------------------
/**
* Returns the free space on a drive or volume in kilobytes by invoking
* the command line.
* <pre>
* FileSystemUtils.freeSpaceKb("C:"); // Windows
* FileSystemUtils.freeSpaceKb("/volume"); // *nix
* </pre>
* The free space is calculated via the command line.
* It uses 'dir /-c' on Windows, 'df -kP' on AIX/HP-UX and 'df -k' on other Unix.
* <p>
* In order to work, you must be running Windows, or have a implementation of
* Unix df that supports GNU format when passed -k (or -kP). If you are going
* to rely on this code, please check that it works on your OS by running
* some simple tests to compare the command line with the output from this class.
* If your operating system isn't supported, please raise a JIRA call detailing
* the exact result from df -k and as much other detail as possible, thanks.
*
* @param path the path to get free space for, not null, not empty on Unix
* @return the amount of free drive space on the drive or volume in kilobytes
* @throws IllegalArgumentException if the path is invalid
* @throws IllegalStateException if an error occurred in initialisation
* @throws IOException if an error occurs when finding the free space
* @since Commons IO 1.2, enhanced OS support in 1.3
*/
public static long freeSpaceKb(String path) throws IOException {
return INSTANCE.freeSpaceOS(path, OS, true);
}
//-----------------------------------------------------------------------
/**
* Returns the free space on a drive or volume in a cross-platform manner.
* Note that some OS's are NOT currently supported, including OS/390.
* <pre>
* FileSystemUtils.freeSpace("C:"); // Windows
* FileSystemUtils.freeSpace("/volume"); // *nix
* </pre>
* The free space is calculated via the command line.
* It uses 'dir /-c' on Windows and 'df' on *nix.
*
* @param path the path to get free space for, not null, not empty on Unix
* @param os the operating system code
* @param kb whether to normalize to kilobytes
* @return the amount of free drive space on the drive or volume
* @throws IllegalArgumentException if the path is invalid
* @throws IllegalStateException if an error occurred in initialisation
* @throws IOException if an error occurs when finding the free space
*/
long freeSpaceOS(String path, int os, boolean kb) throws IOException {
if (path == null) {
throw new IllegalArgumentException("Path must not be empty");
}
switch (os) {
case WINDOWS:
return (kb ? freeSpaceWindows(path) / 1024 : freeSpaceWindows(path));
case UNIX:
return freeSpaceUnix(path, kb, false);
case POSIX_UNIX:
return freeSpaceUnix(path, kb, true);
case OTHER:
throw new IllegalStateException("Unsupported operating system");
default:
throw new IllegalStateException(
"Exception caught when determining operating system");
}
}
//-----------------------------------------------------------------------
/**
* Find free space on the Windows platform using the 'dir' command.
*
* @param path the path to get free space for, including the colon
* @return the amount of free drive space on the drive
* @throws IOException if an error occurs
*/
long freeSpaceWindows(String path) throws IOException {
path = FilenameUtils.normalize(path);
if (path.length() > 2 && path.charAt(1) == ':') {
path = path.substring(0, 2); // seems to make it work
}
// build and run the 'dir' command
String[] cmdAttribs = new String[] {"cmd.exe", "/C", "dir /-c " + path};
// read in the output of the command to an ArrayList
List lines = performCommand(cmdAttribs, Integer.MAX_VALUE);
// now iterate over the lines we just read and find the LAST
// non-empty line (the free space bytes should be in the last element
// of the ArrayList anyway, but this will ensure it works even if it's
// not, still assuming it is on the last non-blank line)
for (int i = lines.size() - 1; i >= 0; i--) {
String line = (String) lines.get(i);
if (line.length() > 0) {
return parseDir(line, path);
}
}
// all lines are blank
throw new IOException(
"Command line 'dir /-c' did not return any info " +
"for path '" + path + "'");
}
/**
* Parses the Windows dir response last line
*
* @param line the line to parse
* @param path the path that was sent
* @return the number of bytes
* @throws IOException if an error occurs
*/
long parseDir(String line, String path) throws IOException {
// read from the end of the line to find the last numeric
// character on the line, then continue until we find the first
// non-numeric character, and everything between that and the last
// numeric character inclusive is our free space bytes count
int bytesStart = 0;
int bytesEnd = 0;
int j = line.length() - 1;
innerLoop1: while (j >= 0) {
char c = line.charAt(j);
if (Character.isDigit(c)) {
// found the last numeric character, this is the end of
// the free space bytes count
bytesEnd = j + 1;
break innerLoop1;
}
j--;
}
innerLoop2: while (j >= 0) {
char c = line.charAt(j);
if (!Character.isDigit(c) && c != ',' && c != '.') {
// found the next non-numeric character, this is the
// beginning of the free space bytes count
bytesStart = j + 1;
break innerLoop2;
}
j--;
}
if (j < 0) {
throw new IOException(
"Command line 'dir /-c' did not return valid info " +
"for path '" + path + "'");
}
// remove commas and dots in the bytes count
StringBuffer buf = new StringBuffer(line.substring(bytesStart, bytesEnd));
for (int k = 0; k < buf.length(); k++) {
if (buf.charAt(k) == ',' || buf.charAt(k) == '.') {
buf.deleteCharAt(k--);
}
}
return parseBytes(buf.toString(), path);
}
//-----------------------------------------------------------------------
/**
* Find free space on the *nix platform using the 'df' command.
*
* @param path the path to get free space for
* @param kb whether to normalize to kilobytes
* @param posix whether to use the posix standard format flag
* @return the amount of free drive space on the volume
* @throws IOException if an error occurs
*/
long freeSpaceUnix(String path, boolean kb, boolean posix) throws IOException {
if (path.length() == 0) {
throw new IllegalArgumentException("Path must not be empty");
}
path = FilenameUtils.normalize(path);
// build and run the 'dir' command
String flags = "-";
if (kb) {
flags += "k";
}
if (posix) {
flags += "P";
}
String[] cmdAttribs =
(flags.length() > 1 ? new String[] {"df", flags, path} : new String[] {"df", path});
// perform the command, asking for up to 3 lines (header, interesting, overflow)
List lines = performCommand(cmdAttribs, 3);
if (lines.size() < 2) {
// unknown problem, throw exception
throw new IOException(
"Command line 'df' did not return info as expected " +
"for path '" + path + "'- response was " + lines);
}
String line2 = (String) lines.get(1); // the line we're interested in
// Now, we tokenize the string. The fourth element is what we want.
StringTokenizer tok = new StringTokenizer(line2, " ");
if (tok.countTokens() < 4) {
// could be long Filesystem, thus data on third line
if (tok.countTokens() == 1 && lines.size() >= 3) {
String line3 = (String) lines.get(2); // the line may be interested in
tok = new StringTokenizer(line3, " ");
} else {
throw new IOException(
"Command line 'df' did not return data as expected " +
"for path '" + path + "'- check path is valid");
}
} else {
tok.nextToken(); // Ignore Filesystem
}
tok.nextToken(); // Ignore 1K-blocks
tok.nextToken(); // Ignore Used
String freeSpace = tok.nextToken();
return parseBytes(freeSpace, path);
}
//-----------------------------------------------------------------------
/**
* Parses the bytes from a string.
*
* @param freeSpace the free space string
* @param path the path
* @return the number of bytes
* @throws IOException if an error occurs
*/
long parseBytes(String freeSpace, String path) throws IOException {
try {
long bytes = Long.parseLong(freeSpace);
if (bytes < 0) {
throw new IOException(
"Command line 'df' did not find free space in response " +
"for path '" + path + "'- check path is valid");
}
return bytes;
} catch (NumberFormatException ex) {
throw new IOException(
"Command line 'df' did not return numeric data as expected " +
"for path '" + path + "'- check path is valid");
}
}
//-----------------------------------------------------------------------
/**
* Performs the os command.
*
* @param cmdAttribs the command line parameters
* @param max The maximum limit for the lines returned
* @return the parsed data
* @throws IOException if an error occurs
*/
List performCommand(String[] cmdAttribs, int max) throws IOException {
// this method does what it can to avoid the 'Too many open files' error
// based on trial and error and these links:
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4801027
// http://forum.java.sun.com/thread.jspa?threadID=533029&messageID=2572018
// however, its still not perfect as the JDK support is so poor
// (see commond-exec or ant for a better multi-threaded multi-os solution)
List lines = new ArrayList(20);
Process proc = null;
InputStream in = null;
OutputStream out = null;
InputStream err = null;
BufferedReader inr = null;
try {
proc = openProcess(cmdAttribs);
in = proc.getInputStream();
out = proc.getOutputStream();
err = proc.getErrorStream();
inr = new BufferedReader(new InputStreamReader(in));
String line = inr.readLine();
while (line != null && lines.size() < max) {
line = line.toLowerCase().trim();
lines.add(line);
line = inr.readLine();
}
proc.waitFor();
if (proc.exitValue() != 0) {
// os command problem, throw exception
throw new IOException(
"Command line returned OS error code '" + proc.exitValue() +
"' for command " + Arrays.asList(cmdAttribs));
}
if (lines.size() == 0) {
// unknown problem, throw exception
throw new IOException(
"Command line did not return any info " +
"for command " + Arrays.asList(cmdAttribs));
}
return lines;
} catch (InterruptedException ex) {
throw new IOException(
"Command line threw an InterruptedException '" + ex.getMessage() +
"' for command " + Arrays.asList(cmdAttribs));
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(err);
IOUtils.closeQuietly(inr);
if (proc != null) {
proc.destroy();
}
}
}
/**
* Opens the process to the operating system.
*
* @param cmdAttribs the command line parameters
* @return the process
* @throws IOException if an error occurs
*/
Process openProcess(String[] cmdAttribs) throws IOException {
return Runtime.getRuntime().exec(cmdAttribs);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,149 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io;
import java.io.IOException;
import java.io.OutputStream;
/**
* Dumps data in hexadecimal format.
* <p>
* Provides a single function to take an array of bytes and display it
* in hexadecimal form.
* <p>
* Origin of code: POI.
*
* @author Scott Sanders
* @author Marc Johnson
* @version $Id: HexDump.java 596667 2007-11-20 13:50:14Z niallp $
*/
public class HexDump {
/**
* Instances should NOT be constructed in standard programming.
*/
public HexDump() {
super();
}
/**
* Dump an array of bytes to an OutputStream.
*
* @param data the byte array to be dumped
* @param offset its offset, whatever that might mean
* @param stream the OutputStream to which the data is to be
* written
* @param index initial index into the byte array
*
* @throws IOException is thrown if anything goes wrong writing
* the data to stream
* @throws ArrayIndexOutOfBoundsException if the index is
* outside the data array's bounds
* @throws IllegalArgumentException if the output stream is null
*/
public static void dump(byte[] data, long offset,
OutputStream stream, int index)
throws IOException, ArrayIndexOutOfBoundsException,
IllegalArgumentException {
if ((index < 0) || (index >= data.length)) {
throw new ArrayIndexOutOfBoundsException(
"illegal index: " + index + " into array of length "
+ data.length);
}
if (stream == null) {
throw new IllegalArgumentException("cannot write to nullstream");
}
long display_offset = offset + index;
StringBuffer buffer = new StringBuffer(74);
for (int j = index; j < data.length; j += 16) {
int chars_read = data.length - j;
if (chars_read > 16) {
chars_read = 16;
}
dump(buffer, display_offset).append(' ');
for (int k = 0; k < 16; k++) {
if (k < chars_read) {
dump(buffer, data[k + j]);
} else {
buffer.append(" ");
}
buffer.append(' ');
}
for (int k = 0; k < chars_read; k++) {
if ((data[k + j] >= ' ') && (data[k + j] < 127)) {
buffer.append((char) data[k + j]);
} else {
buffer.append('.');
}
}
buffer.append(EOL);
stream.write(buffer.toString().getBytes());
stream.flush();
buffer.setLength(0);
display_offset += chars_read;
}
}
/**
* The line-separator (initializes to "line.separator" system property.
*/
public static final String EOL =
System.getProperty("line.separator");
private static final char[] _hexcodes =
{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'
};
private static final int[] _shifts =
{
28, 24, 20, 16, 12, 8, 4, 0
};
/**
* Dump a long value into a StringBuffer.
*
* @param _lbuffer the StringBuffer to dump the value in
* @param value the long value to be dumped
* @return StringBuffer containing the dumped value.
*/
private static StringBuffer dump(StringBuffer _lbuffer, long value) {
for (int j = 0; j < 8; j++) {
_lbuffer
.append(_hexcodes[((int) (value >> _shifts[j])) & 15]);
}
return _lbuffer;
}
/**
* Dump a byte value into a StringBuffer.
*
* @param _cbuffer the StringBuffer to dump the value in
* @param value the byte value to be dumped
* @return StringBuffer containing the dumped value.
*/
private static StringBuffer dump(StringBuffer _cbuffer, byte value) {
for (int j = 0; j < 2; j++) {
_cbuffer.append(_hexcodes[(value >> _shifts[j + 6]) & 15]);
}
return _cbuffer;
}
}

View File

@ -1,238 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io;
import java.io.Serializable;
/**
* Enumeration of IO case sensitivity.
* <p>
* Different filing systems have different rules for case-sensitivity.
* Windows is case-insensitive, Unix is case-sensitive.
* <p>
* This class captures that difference, providing an enumeration to
* control how filename comparisons should be performed. It also provides
* methods that use the enumeration to perform comparisons.
* <p>
* Wherever possible, you should use the <code>check</code> methods in this
* class to compare filenames.
*
* @author Stephen Colebourne
* @version $Id: IOCase.java 606345 2007-12-21 23:43:01Z ggregory $
* @since Commons IO 1.3
*/
public final class IOCase implements Serializable {
/**
* The constant for case sensitive regardless of operating system.
*/
public static final IOCase SENSITIVE = new IOCase("Sensitive", true);
/**
* The constant for case insensitive regardless of operating system.
*/
public static final IOCase INSENSITIVE = new IOCase("Insensitive", false);
/**
* The constant for case sensitivity determined by the current operating system.
* Windows is case-insensitive when comparing filenames, Unix is case-sensitive.
* <p>
* If you derialize this constant of Windows, and deserialize on Unix, or vice
* versa, then the value of the case-sensitivity flag will change.
*/
public static final IOCase SYSTEM = new IOCase("System", !FilenameUtils.isSystemWindows());
/** Serialization version. */
private static final long serialVersionUID = -6343169151696340687L;
/** The enumeration name. */
private final String name;
/** The sensitivity flag. */
private final transient boolean sensitive;
//-----------------------------------------------------------------------
/**
* Factory method to create an IOCase from a name.
*
* @param name the name to find
* @return the IOCase object
* @throws IllegalArgumentException if the name is invalid
*/
public static IOCase forName(String name) {
if (IOCase.SENSITIVE.name.equals(name)){
return IOCase.SENSITIVE;
}
if (IOCase.INSENSITIVE.name.equals(name)){
return IOCase.INSENSITIVE;
}
if (IOCase.SYSTEM.name.equals(name)){
return IOCase.SYSTEM;
}
throw new IllegalArgumentException("Invalid IOCase name: " + name);
}
//-----------------------------------------------------------------------
/**
* Private constructor.
*
* @param name the name
* @param sensitive the sensitivity
*/
private IOCase(String name, boolean sensitive) {
this.name = name;
this.sensitive = sensitive;
}
/**
* Replaces the enumeration from the stream with a real one.
* This ensures that the correct flag is set for SYSTEM.
*
* @return the resolved object
*/
private Object readResolve() {
return forName(name);
}
//-----------------------------------------------------------------------
/**
* Gets the name of the constant.
*
* @return the name of the constant
*/
public String getName() {
return name;
}
/**
* Does the object represent case sensitive comparison.
*
* @return true if case sensitive
*/
public boolean isCaseSensitive() {
return sensitive;
}
//-----------------------------------------------------------------------
/**
* Compares two strings using the case-sensitivity rule.
* <p>
* This method mimics {@link String#compareTo} but takes case-sensitivity
* into account.
*
* @param str1 the first string to compare, not null
* @param str2 the second string to compare, not null
* @return true if equal using the case rules
* @throws NullPointerException if either string is null
*/
public int checkCompareTo(String str1, String str2) {
if (str1 == null || str2 == null) {
throw new NullPointerException("The strings must not be null");
}
return sensitive ? str1.compareTo(str2) : str1.compareToIgnoreCase(str2);
}
/**
* Compares two strings using the case-sensitivity rule.
* <p>
* This method mimics {@link String#equals} but takes case-sensitivity
* into account.
*
* @param str1 the first string to compare, not null
* @param str2 the second string to compare, not null
* @return true if equal using the case rules
* @throws NullPointerException if either string is null
*/
public boolean checkEquals(String str1, String str2) {
if (str1 == null || str2 == null) {
throw new NullPointerException("The strings must not be null");
}
return sensitive ? str1.equals(str2) : str1.equalsIgnoreCase(str2);
}
/**
* Checks if one string starts with another using the case-sensitivity rule.
* <p>
* This method mimics {@link String#startsWith(String)} but takes case-sensitivity
* into account.
*
* @param str the string to check, not null
* @param start the start to compare against, not null
* @return true if equal using the case rules
* @throws NullPointerException if either string is null
*/
public boolean checkStartsWith(String str, String start) {
return str.regionMatches(!sensitive, 0, start, 0, start.length());
}
/**
* Checks if one string ends with another using the case-sensitivity rule.
* <p>
* This method mimics {@link String#endsWith} but takes case-sensitivity
* into account.
*
* @param str the string to check, not null
* @param end the end to compare against, not null
* @return true if equal using the case rules
* @throws NullPointerException if either string is null
*/
public boolean checkEndsWith(String str, String end) {
int endLen = end.length();
return str.regionMatches(!sensitive, str.length() - endLen, end, 0, endLen);
}
/**
* Checks if one string contains another at a specific index using the case-sensitivity rule.
* <p>
* This method mimics parts of {@link String#regionMatches(boolean, int, String, int, int)}
* but takes case-sensitivity into account.
*
* @param str the string to check, not null
* @param strStartIndex the index to start at in str
* @param search the start to search for, not null
* @return true if equal using the case rules
* @throws NullPointerException if either string is null
*/
public boolean checkRegionMatches(String str, int strStartIndex, String search) {
return str.regionMatches(!sensitive, strStartIndex, search, 0, search.length());
}
/**
* Converts the case of the input String to a standard format.
* Subsequent operations can then use standard String methods.
*
* @param str the string to convert, null returns null
* @return the lower-case version if case-insensitive
*/
String convertCase(String str) {
if (str == null) {
return null;
}
return sensitive ? str : str.toLowerCase();
}
//-----------------------------------------------------------------------
/**
* Gets a string describing the sensitivity.
*
* @return a string describing the sensitivity
*/
public String toString() {
return name;
}
}

View File

@ -1,69 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io;
import java.io.IOException;
/**
* Subclasses IOException with the {@link Throwable} constructors missing before Java 6. If you are using Java 6,
* consider this class deprecated and use {@link IOException}.
*
* @author <a href="http://commons.apache.org/io/">Apache Commons IO</a>
* @version $Id$
* @since Commons IO 1.4
*/
public class IOExceptionWithCause extends IOException {
/**
* Defines the serial version UID.
*/
private static final long serialVersionUID = 1L;
/**
* Constructs a new instance with the given message and cause.
* <p>
* As specified in {@link Throwable}, the message in the given <code>cause</code> is not used in this instance's
* message.
* </p>
*
* @param message
* the message (see {@link #getMessage()})
* @param cause
* the cause (see {@link #getCause()}). A <code>null</code> value is allowed.
*/
public IOExceptionWithCause(String message, Throwable cause) {
super(message);
this.initCause(cause);
}
/**
* Constructs a new instance with the given cause.
* <p>
* The message is set to <code>cause==null ? null : cause.toString()</code>, which by default contains the class
* and message of <code>cause</code>. This constructor is useful for call sites that just wrap another throwable.
* </p>
*
* @param cause
* the cause (see {@link #getCause()}). A <code>null</code> value is allowed.
*/
public IOExceptionWithCause(Throwable cause) {
super(cause == null ? null : cause.toString());
this.initCause(cause);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,181 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* An Iterator over the lines in a <code>Reader</code>.
* <p>
* <code>LineIterator</code> holds a reference to an open <code>Reader</code>.
* When you have finished with the iterator you should close the reader
* to free internal resources. This can be done by closing the reader directly,
* or by calling the {@link #close()} or {@link #closeQuietly(LineIterator)}
* method on the iterator.
* <p>
* The recommended usage pattern is:
* <pre>
* LineIterator it = FileUtils.lineIterator(file, "UTF-8");
* try {
* while (it.hasNext()) {
* String line = it.nextLine();
* /// do something with line
* }
* } finally {
* LineIterator.closeQuietly(iterator);
* }
* </pre>
*
* @author Niall Pemberton
* @author Stephen Colebourne
* @author Sandy McArthur
* @version $Id: LineIterator.java 437567 2006-08-28 06:39:07Z bayard $
* @since Commons IO 1.2
*/
public class LineIterator implements Iterator {
/** The reader that is being read. */
private final BufferedReader bufferedReader;
/** The current line. */
private String cachedLine;
/** A flag indicating if the iterator has been fully read. */
private boolean finished = false;
/**
* Constructs an iterator of the lines for a <code>Reader</code>.
*
* @param reader the <code>Reader</code> to read from, not null
* @throws IllegalArgumentException if the reader is null
*/
public LineIterator(final Reader reader) throws IllegalArgumentException {
if (reader == null) {
throw new IllegalArgumentException("Reader must not be null");
}
if (reader instanceof BufferedReader) {
bufferedReader = (BufferedReader) reader;
} else {
bufferedReader = new BufferedReader(reader);
}
}
//-----------------------------------------------------------------------
/**
* Indicates whether the <code>Reader</code> has more lines.
* If there is an <code>IOException</code> then {@link #close()} will
* be called on this instance.
*
* @return <code>true</code> if the Reader has more lines
* @throws IllegalStateException if an IO exception occurs
*/
public boolean hasNext() {
if (cachedLine != null) {
return true;
} else if (finished) {
return false;
} else {
try {
while (true) {
String line = bufferedReader.readLine();
if (line == null) {
finished = true;
return false;
} else if (isValidLine(line)) {
cachedLine = line;
return true;
}
}
} catch(IOException ioe) {
close();
throw new IllegalStateException(ioe.toString());
}
}
}
/**
* Overridable method to validate each line that is returned.
*
* @param line the line that is to be validated
* @return true if valid, false to remove from the iterator
*/
protected boolean isValidLine(String line) {
return true;
}
/**
* Returns the next line in the wrapped <code>Reader</code>.
*
* @return the next line from the input
* @throws NoSuchElementException if there is no line to return
*/
public Object next() {
return nextLine();
}
/**
* Returns the next line in the wrapped <code>Reader</code>.
*
* @return the next line from the input
* @throws NoSuchElementException if there is no line to return
*/
public String nextLine() {
if (!hasNext()) {
throw new NoSuchElementException("No more lines");
}
String currentLine = cachedLine;
cachedLine = null;
return currentLine;
}
/**
* Closes the underlying <code>Reader</code> quietly.
* This method is useful if you only want to process the first few
* lines of a larger file. If you do not close the iterator
* then the <code>Reader</code> remains open.
* This method can safely be called multiple times.
*/
public void close() {
finished = true;
IOUtils.closeQuietly(bufferedReader);
cachedLine = null;
}
/**
* Unsupported.
*
* @throws UnsupportedOperationException always
*/
public void remove() {
throw new UnsupportedOperationException("Remove unsupported on LineIterator");
}
//-----------------------------------------------------------------------
/**
* Closes the iterator, handling null and ignoring exceptions.
*
* @param iterator the iterator to close
*/
public static void closeQuietly(LineIterator iterator) {
if (iterator != null) {
iterator.close();
}
}
}

View File

@ -1,68 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.comparator;
import java.io.File;
import java.io.Serializable;
import java.util.Comparator;
/**
* Compare two files using the <b>default</b> {@link File#compareTo(File)} method.
* <p>
* This comparator can be used to sort lists or arrays of files
* by using the default file comparison.
* <p>
* Example of sorting a list of files using the
* {@link #DEFAULT_COMPARATOR} singleton instance:
* <pre>
* List&lt;File&gt; list = ...
* Collections.sort(list, DefaultFileComparator.DEFAULT_COMPARATOR);
* </pre>
* <p>
* Example of doing a <i>reverse</i> sort of an array of files using the
* {@link #DEFAULT_REVERSE} singleton instance:
* <pre>
* File[] array = ...
* Arrays.sort(array, DefaultFileComparator.DEFAULT_REVERSE);
* </pre>
* <p>
*
* @version $Revision: 609243 $ $Date: 2008-01-06 00:30:42 +0000 (Sun, 06 Jan 2008) $
* @since Commons IO 1.4
*/
public class DefaultFileComparator implements Comparator, Serializable {
/** Singleton default comparator instance */
public static final Comparator DEFAULT_COMPARATOR = new DefaultFileComparator();
/** Singleton reverse default comparator instance */
public static final Comparator DEFAULT_REVERSE = new ReverseComparator(DEFAULT_COMPARATOR);
/**
* Compare the two files using the {@link File#compareTo(File)} method.
*
* @param obj1 The first file to compare
* @param obj2 The second file to compare
* @return the result of calling file1's
* {@link File#compareTo(File)} with file2 as the parameter.
*/
public int compare(Object obj1, Object obj2) {
File file1 = (File)obj1;
File file2 = (File)obj2;
return file1.compareTo(file2);
}
}

View File

@ -1,112 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.comparator;
import java.io.File;
import java.io.Serializable;
import java.util.Comparator;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOCase;
/**
* Compare the file name <b>extensions</b> for order
* (see {@link FilenameUtils#getExtension(String)}).
* <p>
* This comparator can be used to sort lists or arrays of files
* by their file extension either in a case-sensitive, case-insensitive or
* system dependant case sensitive way. A number of singleton instances
* are provided for the various case sensitivity options (using {@link IOCase})
* and the reverse of those options.
* <p>
* Example of a <i>case-sensitive</i> file extension sort using the
* {@link #EXTENSION_COMPARATOR} singleton instance:
* <pre>
* List&lt;File&gt; list = ...
* Collections.sort(list, ExtensionFileComparator.EXTENSION_COMPARATOR);
* </pre>
* <p>
* Example of a <i>reverse case-insensitive</i> file extension sort using the
* {@link #EXTENSION_INSENSITIVE_REVERSE} singleton instance:
* <pre>
* File[] array = ...
* Arrays.sort(array, ExtensionFileComparator.EXTENSION_INSENSITIVE_REVERSE);
* </pre>
* <p>
*
* @version $Revision: 609243 $ $Date: 2008-01-06 00:30:42 +0000 (Sun, 06 Jan 2008) $
* @since Commons IO 1.4
*/
public class ExtensionFileComparator implements Comparator, Serializable {
/** Case-sensitive extension comparator instance (see {@link IOCase#SENSITIVE}) */
public static final Comparator EXTENSION_COMPARATOR = new ExtensionFileComparator();
/** Reverse case-sensitive extension comparator instance (see {@link IOCase#SENSITIVE}) */
public static final Comparator EXTENSION_REVERSE = new ReverseComparator(EXTENSION_COMPARATOR);
/** Case-insensitive extension comparator instance (see {@link IOCase#INSENSITIVE}) */
public static final Comparator EXTENSION_INSENSITIVE_COMPARATOR = new ExtensionFileComparator(IOCase.INSENSITIVE);
/** Reverse case-insensitive extension comparator instance (see {@link IOCase#INSENSITIVE}) */
public static final Comparator EXTENSION_INSENSITIVE_REVERSE
= new ReverseComparator(EXTENSION_INSENSITIVE_COMPARATOR);
/** System sensitive extension comparator instance (see {@link IOCase#SYSTEM}) */
public static final Comparator EXTENSION_SYSTEM_COMPARATOR = new ExtensionFileComparator(IOCase.SYSTEM);
/** Reverse system sensitive path comparator instance (see {@link IOCase#SYSTEM}) */
public static final Comparator EXTENSION_SYSTEM_REVERSE = new ReverseComparator(EXTENSION_SYSTEM_COMPARATOR);
/** Whether the comparison is case sensitive. */
private final IOCase caseSensitivity;
/**
* Construct a case sensitive file extension comparator instance.
*/
public ExtensionFileComparator() {
this.caseSensitivity = IOCase.SENSITIVE;
}
/**
* Construct a file extension comparator instance with the specified case-sensitivity.
*
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
*/
public ExtensionFileComparator(IOCase caseSensitivity) {
this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity;
}
/**
* Compare the extensions of two files the specified case sensitivity.
*
* @param obj1 The first file to compare
* @param obj2 The second file to compare
* @return a negative value if the first file's extension
* is less than the second, zero if the extensions are the
* same and a positive value if the first files extension
* is greater than the second file.
*
*/
public int compare(Object obj1, Object obj2) {
File file1 = (File)obj1;
File file2 = (File)obj2;
String suffix1 = FilenameUtils.getExtension(file1.getName());
String suffix2 = FilenameUtils.getExtension(file2.getName());
return caseSensitivity.checkCompareTo(suffix1, suffix2);
}
}

View File

@ -1,79 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.comparator;
import java.io.File;
import java.io.Serializable;
import java.util.Comparator;
/**
* Compare the <b>last modified date/time</b> of two files for order
* (see {@link File#lastModified()}).
* <p>
* This comparator can be used to sort lists or arrays of files
* by their last modified date/time.
* <p>
* Example of sorting a list of files using the
* {@link #LASTMODIFIED_COMPARATOR} singleton instance:
* <pre>
* List&lt;File&gt; list = ...
* Collections.sort(list, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
* </pre>
* <p>
* Example of doing a <i>reverse</i> sort of an array of files using the
* {@link #LASTMODIFIED_REVERSE} singleton instance:
* <pre>
* File[] array = ...
* Arrays.sort(array, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
* </pre>
* <p>
*
* @version $Revision: 609243 $ $Date: 2008-01-06 00:30:42 +0000 (Sun, 06 Jan 2008) $
* @since Commons IO 1.4
*/
public class LastModifiedFileComparator implements Comparator, Serializable {
/** Last modified comparator instance */
public static final Comparator LASTMODIFIED_COMPARATOR = new LastModifiedFileComparator();
/** Reverse last modified comparator instance */
public static final Comparator LASTMODIFIED_REVERSE = new ReverseComparator(LASTMODIFIED_COMPARATOR);
/**
* Compare the last the last modified date/time of two files.
*
* @param obj1 The first file to compare
* @param obj2 The second file to compare
* @return a negative value if the first file's lastmodified date/time
* is less than the second, zero if the lastmodified date/time are the
* same and a positive value if the first files lastmodified date/time
* is greater than the second file.
*
*/
public int compare(Object obj1, Object obj2) {
File file1 = (File)obj1;
File file2 = (File)obj2;
long result = file1.lastModified() - file2.lastModified();
if (result < 0) {
return -1;
} else if (result > 0) {
return 1;
} else {
return 0;
}
}
}

View File

@ -1,106 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.comparator;
import java.io.File;
import java.io.Serializable;
import java.util.Comparator;
import org.apache.commons.io.IOCase;
/**
* Compare the <b>names</b> of two files for order (see {@link File#getName()}).
* <p>
* This comparator can be used to sort lists or arrays of files
* by their name either in a case-sensitive, case-insensitive or
* system dependant case sensitive way. A number of singleton instances
* are provided for the various case sensitivity options (using {@link IOCase})
* and the reverse of those options.
* <p>
* Example of a <i>case-sensitive</i> file name sort using the
* {@link #NAME_COMPARATOR} singleton instance:
* <pre>
* List&lt;File&gt; list = ...
* Collections.sort(list, NameFileComparator.NAME_COMPARATOR);
* </pre>
* <p>
* Example of a <i>reverse case-insensitive</i> file name sort using the
* {@link #NAME_INSENSITIVE_REVERSE} singleton instance:
* <pre>
* File[] array = ...
* Arrays.sort(array, NameFileComparator.NAME_INSENSITIVE_REVERSE);
* </pre>
* <p>
*
* @version $Revision: 609243 $ $Date: 2008-01-06 00:30:42 +0000 (Sun, 06 Jan 2008) $
* @since Commons IO 1.4
*/
public class NameFileComparator implements Comparator, Serializable {
/** Case-sensitive name comparator instance (see {@link IOCase#SENSITIVE}) */
public static final Comparator NAME_COMPARATOR = new NameFileComparator();
/** Reverse case-sensitive name comparator instance (see {@link IOCase#SENSITIVE}) */
public static final Comparator NAME_REVERSE = new ReverseComparator(NAME_COMPARATOR);
/** Case-insensitive name comparator instance (see {@link IOCase#INSENSITIVE}) */
public static final Comparator NAME_INSENSITIVE_COMPARATOR = new NameFileComparator(IOCase.INSENSITIVE);
/** Reverse case-insensitive name comparator instance (see {@link IOCase#INSENSITIVE}) */
public static final Comparator NAME_INSENSITIVE_REVERSE = new ReverseComparator(NAME_INSENSITIVE_COMPARATOR);
/** System sensitive name comparator instance (see {@link IOCase#SYSTEM}) */
public static final Comparator NAME_SYSTEM_COMPARATOR = new NameFileComparator(IOCase.SYSTEM);
/** Reverse system sensitive name comparator instance (see {@link IOCase#SYSTEM}) */
public static final Comparator NAME_SYSTEM_REVERSE = new ReverseComparator(NAME_SYSTEM_COMPARATOR);
/** Whether the comparison is case sensitive. */
private final IOCase caseSensitivity;
/**
* Construct a case sensitive file name comparator instance.
*/
public NameFileComparator() {
this.caseSensitivity = IOCase.SENSITIVE;
}
/**
* Construct a file name comparator instance with the specified case-sensitivity.
*
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
*/
public NameFileComparator(IOCase caseSensitivity) {
this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity;
}
/**
* Compare the names of two files with the specified case sensitivity.
*
* @param obj1 The first file to compare
* @param obj2 The second file to compare
* @return a negative value if the first file's name
* is less than the second, zero if the names are the
* same and a positive value if the first files name
* is greater than the second file.
*/
public int compare(Object obj1, Object obj2) {
File file1 = (File)obj1;
File file2 = (File)obj2;
return caseSensitivity.checkCompareTo(file1.getName(), file2.getName());
}
}

View File

@ -1,107 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.comparator;
import java.io.File;
import java.io.Serializable;
import java.util.Comparator;
import org.apache.commons.io.IOCase;
/**
* Compare the <b>path</b> of two files for order (see {@link File#getPath()}).
* <p>
* This comparator can be used to sort lists or arrays of files
* by their path either in a case-sensitive, case-insensitive or
* system dependant case sensitive way. A number of singleton instances
* are provided for the various case sensitivity options (using {@link IOCase})
* and the reverse of those options.
* <p>
* Example of a <i>case-sensitive</i> file path sort using the
* {@link #PATH_COMPARATOR} singleton instance:
* <pre>
* List&lt;File&gt; list = ...
* Collections.sort(list, PathFileComparator.PATH_COMPARATOR);
* </pre>
* <p>
* Example of a <i>reverse case-insensitive</i> file path sort using the
* {@link #PATH_INSENSITIVE_REVERSE} singleton instance:
* <pre>
* File[] array = ...
* Arrays.sort(array, PathFileComparator.PATH_INSENSITIVE_REVERSE);
* </pre>
* <p>
*
* @version $Revision: 609243 $ $Date: 2008-01-06 00:30:42 +0000 (Sun, 06 Jan 2008) $
* @since Commons IO 1.4
*/
public class PathFileComparator implements Comparator, Serializable {
/** Case-sensitive path comparator instance (see {@link IOCase#SENSITIVE}) */
public static final Comparator PATH_COMPARATOR = new PathFileComparator();
/** Reverse case-sensitive path comparator instance (see {@link IOCase#SENSITIVE}) */
public static final Comparator PATH_REVERSE = new ReverseComparator(PATH_COMPARATOR);
/** Case-insensitive path comparator instance (see {@link IOCase#INSENSITIVE}) */
public static final Comparator PATH_INSENSITIVE_COMPARATOR = new PathFileComparator(IOCase.INSENSITIVE);
/** Reverse case-insensitive path comparator instance (see {@link IOCase#INSENSITIVE}) */
public static final Comparator PATH_INSENSITIVE_REVERSE = new ReverseComparator(PATH_INSENSITIVE_COMPARATOR);
/** System sensitive path comparator instance (see {@link IOCase#SYSTEM}) */
public static final Comparator PATH_SYSTEM_COMPARATOR = new PathFileComparator(IOCase.SYSTEM);
/** Reverse system sensitive path comparator instance (see {@link IOCase#SYSTEM}) */
public static final Comparator PATH_SYSTEM_REVERSE = new ReverseComparator(PATH_SYSTEM_COMPARATOR);
/** Whether the comparison is case sensitive. */
private final IOCase caseSensitivity;
/**
* Construct a case sensitive file path comparator instance.
*/
public PathFileComparator() {
this.caseSensitivity = IOCase.SENSITIVE;
}
/**
* Construct a file path comparator instance with the specified case-sensitivity.
*
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
*/
public PathFileComparator(IOCase caseSensitivity) {
this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity;
}
/**
* Compare the paths of two files the specified case sensitivity.
*
* @param obj1 The first file to compare
* @param obj2 The second file to compare
* @return a negative value if the first file's path
* is less than the second, zero if the paths are the
* same and a positive value if the first files path
* is greater than the second file.
*
*/
public int compare(Object obj1, Object obj2) {
File file1 = (File)obj1;
File file2 = (File)obj2;
return caseSensitivity.checkCompareTo(file1.getPath(), file2.getPath());
}
}

View File

@ -1,57 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.comparator;
import java.io.Serializable;
import java.util.Comparator;
/**
* Reverses the result of comparing two objects using
* the delegate {@link Comparator}.
*
* @version $Revision: 609243 $ $Date: 2008-01-06 00:30:42 +0000 (Sun, 06 Jan 2008) $
* @since Commons IO 1.4
*/
class ReverseComparator implements Comparator, Serializable {
private final Comparator delegate;
/**
* Construct an instance with the sepecified delegate {@link Comparator}.
*
* @param delegate The comparator to delegate to
*/
public ReverseComparator(Comparator delegate) {
if (delegate == null) {
throw new IllegalArgumentException("Delegate comparator is missing");
}
this.delegate = delegate;
}
/**
* Compare using the delegate Comparator, but reversing the result.
*
* @param obj1 The first object to compare
* @param obj2 The second object to compare
* @return the result from the delegate {@link Comparator#compare(Object, Object)}
* reversing the value (i.e. positive becomes negative and vice versa)
*/
public int compare(Object obj1, Object obj2) {
return delegate.compare(obj2, obj1); // parameters switched round
}
}

View File

@ -1,132 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.comparator;
import java.io.File;
import java.io.Serializable;
import java.util.Comparator;
import org.apache.commons.io.FileUtils;
/**
* Compare the <b>length/size</b> of two files for order (see
* {@link File#length()} and {@link FileUtils#sizeOfDirectory(File)}).
* <p>
* This comparator can be used to sort lists or arrays of files
* by their length/size.
* <p>
* Example of sorting a list of files using the
* {@link #SIZE_COMPARATOR} singleton instance:
* <pre>
* List&lt;File&gt; list = ...
* Collections.sort(list, LengthFileComparator.LENGTH_COMPARATOR);
* </pre>
* <p>
* Example of doing a <i>reverse</i> sort of an array of files using the
* {@link #SIZE_REVERSE} singleton instance:
* <pre>
* File[] array = ...
* Arrays.sort(array, LengthFileComparator.LENGTH_REVERSE);
* </pre>
* <p>
* <strong>N.B.</strong> Directories are treated as <b>zero size</b> unless
* <code>sumDirectoryContents</code> is <code>true</code>.
*
* @version $Revision: 609243 $ $Date: 2008-01-06 00:30:42 +0000 (Sun, 06 Jan 2008) $
* @since Commons IO 1.4
*/
public class SizeFileComparator implements Comparator, Serializable {
/** Size comparator instance - directories are treated as zero size */
public static final Comparator SIZE_COMPARATOR = new SizeFileComparator();
/** Reverse size comparator instance - directories are treated as zero size */
public static final Comparator SIZE_REVERSE = new ReverseComparator(SIZE_COMPARATOR);
/**
* Size comparator instance which sums the size of a directory's contents
* using {@link FileUtils#sizeOfDirectory(File)}
*/
public static final Comparator SIZE_SUMDIR_COMPARATOR = new SizeFileComparator(true);
/**
* Reverse size comparator instance which sums the size of a directory's contents
* using {@link FileUtils#sizeOfDirectory(File)}
*/
public static final Comparator SIZE_SUMDIR_REVERSE = new ReverseComparator(SIZE_SUMDIR_COMPARATOR);
/** Whether the sum of the directory's contents should be calculated. */
private final boolean sumDirectoryContents;
/**
* Construct a file size comparator instance (directories treated as zero size).
*/
public SizeFileComparator() {
this.sumDirectoryContents = false;
}
/**
* Construct a file size comparator instance specifying whether the size of
* the directory contents should be aggregated.
* <p>
* If the <code>sumDirectoryContents</code> is <code>true</code> The size of
* directories is calculated using {@link FileUtils#sizeOfDirectory(File)}.
*
* @param sumDirectoryContents <code>true</code> if the sum of the directoryies contents
* should be calculated, otherwise <code>false</code> if directories should be treated
* as size zero (see {@link FileUtils#sizeOfDirectory(File)}).
*/
public SizeFileComparator(boolean sumDirectoryContents) {
this.sumDirectoryContents = sumDirectoryContents;
}
/**
* Compare the length of two files.
*
* @param obj1 The first file to compare
* @param obj2 The second file to compare
* @return a negative value if the first file's length
* is less than the second, zero if the lengths are the
* same and a positive value if the first files length
* is greater than the second file.
*
*/
public int compare(Object obj1, Object obj2) {
File file1 = (File)obj1;
File file2 = (File)obj2;
long size1 = 0;
if (file1.isDirectory()) {
size1 = sumDirectoryContents && file1.exists() ? FileUtils.sizeOfDirectory(file1) : 0;
} else {
size1 = file1.length();
}
long size2 = 0;
if (file2.isDirectory()) {
size2 = sumDirectoryContents && file2.exists() ? FileUtils.sizeOfDirectory(file2) : 0;
} else {
size2 = file2.length();
}
long result = size1 - size2;
if (result < 0) {
return -1;
} else if (result > 0) {
return 1;
} else {
return 0;
}
}
}

View File

@ -1,25 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--
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 compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html>
<body>
<p>This package provides various {@link java.util.Comparator} implementations
for {@link java.io.File}s.
</p>
</body>
</html>

View File

@ -1,67 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
/**
* An abstract class which implements the Java FileFilter and FilenameFilter
* interfaces via the IOFileFilter interface.
* <p>
* Note that a subclass <b>must</b> override one of the accept methods,
* otherwise your class will infinitely loop.
*
* @since Commons IO 1.0
* @version $Revision: 539231 $ $Date: 2007-05-18 04:10:33 +0100 (Fri, 18 May 2007) $
*
* @author Stephen Colebourne
*/
public abstract class AbstractFileFilter implements IOFileFilter {
/**
* Checks to see if the File should be accepted by this filter.
*
* @param file the File to check
* @return true if this file matches the test
*/
public boolean accept(File file) {
return accept(file.getParentFile(), file.getName());
}
/**
* Checks to see if the File should be accepted by this filter.
*
* @param dir the directory File to check
* @param name the filename within the directory to check
* @return true if this file matches the test
*/
public boolean accept(File dir, String name) {
return accept(new File(dir, name));
}
/**
* Provide a String representaion of this file filter.
*
* @return a String representaion
*/
public String toString() {
String name = getClass().getName();
int period = name.lastIndexOf('.');
return (period > 0 ? name.substring(period + 1) : name);
}
}

View File

@ -1,150 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.Date;
import org.apache.commons.io.FileUtils;
/**
* Filters files based on a cutoff time, can filter either newer
* files or files equal to or older.
* <p>
* For example, to print all files and directories in the
* current directory older than one day:
*
* <pre>
* File dir = new File(".");
* // We are interested in files older than one day
* long cutoff = System.currentTimeMillis() - (24 * 60 * 60 * 1000);
* String[] files = dir.list( new AgeFileFilter(cutoff) );
* for ( int i = 0; i &lt; files.length; i++ ) {
* System.out.println(files[i]);
* }
* </pre>
*
* @author Rahul Akolkar
* @version $Id: AgeFileFilter.java 606381 2007-12-22 02:03:16Z ggregory $
* @since Commons IO 1.2
*/
public class AgeFileFilter extends AbstractFileFilter implements Serializable {
/** The cutoff time threshold. */
private final long cutoff;
/** Whether the files accepted will be older or newer. */
private final boolean acceptOlder;
/**
* Constructs a new age file filter for files equal to or older than
* a certain cutoff
*
* @param cutoff the threshold age of the files
*/
public AgeFileFilter(long cutoff) {
this(cutoff, true);
}
/**
* Constructs a new age file filter for files on any one side
* of a certain cutoff.
*
* @param cutoff the threshold age of the files
* @param acceptOlder if true, older files (at or before the cutoff)
* are accepted, else newer ones (after the cutoff).
*/
public AgeFileFilter(long cutoff, boolean acceptOlder) {
this.acceptOlder = acceptOlder;
this.cutoff = cutoff;
}
/**
* Constructs a new age file filter for files older than (at or before)
* a certain cutoff date.
*
* @param cutoffDate the threshold age of the files
*/
public AgeFileFilter(Date cutoffDate) {
this(cutoffDate, true);
}
/**
* Constructs a new age file filter for files on any one side
* of a certain cutoff date.
*
* @param cutoffDate the threshold age of the files
* @param acceptOlder if true, older files (at or before the cutoff)
* are accepted, else newer ones (after the cutoff).
*/
public AgeFileFilter(Date cutoffDate, boolean acceptOlder) {
this(cutoffDate.getTime(), acceptOlder);
}
/**
* Constructs a new age file filter for files older than (at or before)
* a certain File (whose last modification time will be used as reference).
*
* @param cutoffReference the file whose last modification
* time is usesd as the threshold age of the files
*/
public AgeFileFilter(File cutoffReference) {
this(cutoffReference, true);
}
/**
* Constructs a new age file filter for files on any one side
* of a certain File (whose last modification time will be used as
* reference).
*
* @param cutoffReference the file whose last modification
* time is usesd as the threshold age of the files
* @param acceptOlder if true, older files (at or before the cutoff)
* are accepted, else newer ones (after the cutoff).
*/
public AgeFileFilter(File cutoffReference, boolean acceptOlder) {
this(cutoffReference.lastModified(), acceptOlder);
}
//-----------------------------------------------------------------------
/**
* Checks to see if the last modification of the file matches cutoff
* favorably.
* <p>
* If last modification time equals cutoff and newer files are required,
* file <b>IS NOT</b> selected.
* If last modification time equals cutoff and older files are required,
* file <b>IS</b> selected.
*
* @param file the File to check
* @return true if the filename matches
*/
public boolean accept(File file) {
boolean newer = FileUtils.isFileNewer(file, cutoff);
return acceptOlder ? !newer : newer;
}
/**
* Provide a String representaion of this file filter.
*
* @return a String representaion
*/
public String toString() {
String condition = acceptOlder ? "<=" : ">";
return super.toString() + "(" + condition + cutoff + ")";
}
}

View File

@ -1,167 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* A {@link java.io.FileFilter} providing conditional AND logic across a list of
* file filters. This filter returns <code>true</code> if all filters in the
* list return <code>true</code>. Otherwise, it returns <code>false</code>.
* Checking of the file filter list stops when the first filter returns
* <code>false</code>.
*
* @since Commons IO 1.0
* @version $Revision: 606381 $ $Date: 2007-12-22 02:03:16 +0000 (Sat, 22 Dec 2007) $
*
* @author Steven Caswell
*/
public class AndFileFilter
extends AbstractFileFilter
implements ConditionalFileFilter, Serializable {
/** The list of file filters. */
private List fileFilters;
/**
* Constructs a new instance of <code>AndFileFilter</code>.
*
* @since Commons IO 1.1
*/
public AndFileFilter() {
this.fileFilters = new ArrayList();
}
/**
* Constructs a new instance of <code>AndFileFilter</code>
* with the specified list of filters.
*
* @param fileFilters a List of IOFileFilter instances, copied, null ignored
* @since Commons IO 1.1
*/
public AndFileFilter(final List fileFilters) {
if (fileFilters == null) {
this.fileFilters = new ArrayList();
} else {
this.fileFilters = new ArrayList(fileFilters);
}
}
/**
* Constructs a new file filter that ANDs the result of two other filters.
*
* @param filter1 the first filter, must not be null
* @param filter2 the second filter, must not be null
* @throws IllegalArgumentException if either filter is null
*/
public AndFileFilter(IOFileFilter filter1, IOFileFilter filter2) {
if (filter1 == null || filter2 == null) {
throw new IllegalArgumentException("The filters must not be null");
}
this.fileFilters = new ArrayList();
addFileFilter(filter1);
addFileFilter(filter2);
}
/**
* {@inheritDoc}
*/
public void addFileFilter(final IOFileFilter ioFileFilter) {
this.fileFilters.add(ioFileFilter);
}
/**
* {@inheritDoc}
*/
public List getFileFilters() {
return Collections.unmodifiableList(this.fileFilters);
}
/**
* {@inheritDoc}
*/
public boolean removeFileFilter(final IOFileFilter ioFileFilter) {
return this.fileFilters.remove(ioFileFilter);
}
/**
* {@inheritDoc}
*/
public void setFileFilters(final List fileFilters) {
this.fileFilters = new ArrayList(fileFilters);
}
/**
* {@inheritDoc}
*/
public boolean accept(final File file) {
if (this.fileFilters.size() == 0) {
return false;
}
for (Iterator iter = this.fileFilters.iterator(); iter.hasNext();) {
IOFileFilter fileFilter = (IOFileFilter) iter.next();
if (!fileFilter.accept(file)) {
return false;
}
}
return true;
}
/**
* {@inheritDoc}
*/
public boolean accept(final File file, final String name) {
if (this.fileFilters.size() == 0) {
return false;
}
for (Iterator iter = this.fileFilters.iterator(); iter.hasNext();) {
IOFileFilter fileFilter = (IOFileFilter) iter.next();
if (!fileFilter.accept(file, name)) {
return false;
}
}
return true;
}
/**
* Provide a String representaion of this file filter.
*
* @return a String representaion
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(super.toString());
buffer.append("(");
if (fileFilters != null) {
for (int i = 0; i < fileFilters.size(); i++) {
if (i > 0) {
buffer.append(",");
}
Object filter = fileFilters.get(i);
buffer.append(filter == null ? "null" : filter.toString());
}
}
buffer.append(")");
return buffer.toString();
}
}

View File

@ -1,92 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
/**
* This filter accepts <code>File</code>s that can be read.
* <p>
* Example, showing how to print out a list of the
* current directory's <i>readable</i> files:
*
* <pre>
* File dir = new File(".");
* String[] files = dir.list( CanReadFileFilter.CAN_READ );
* for ( int i = 0; i &lt; files.length; i++ ) {
* System.out.println(files[i]);
* }
* </pre>
*
* <p>
* Example, showing how to print out a list of the
* current directory's <i>un-readable</i> files:
*
* <pre>
* File dir = new File(".");
* String[] files = dir.list( CanReadFileFilter.CANNOT_READ );
* for ( int i = 0; i &lt; files.length; i++ ) {
* System.out.println(files[i]);
* }
* </pre>
*
* <p>
* Example, showing how to print out a list of the
* current directory's <i>read-only</i> files:
*
* <pre>
* File dir = new File(".");
* String[] files = dir.list( CanReadFileFilter.READ_ONLY );
* for ( int i = 0; i &lt; files.length; i++ ) {
* System.out.println(files[i]);
* }
* </pre>
*
* @since Commons IO 1.3
* @version $Revision: 587916 $
*/
public class CanReadFileFilter extends AbstractFileFilter implements Serializable {
/** Singleton instance of <i>readable</i> filter */
public static final IOFileFilter CAN_READ = new CanReadFileFilter();
/** Singleton instance of not <i>readable</i> filter */
public static final IOFileFilter CANNOT_READ = new NotFileFilter(CAN_READ);
/** Singleton instance of <i>read-only</i> filter */
public static final IOFileFilter READ_ONLY = new AndFileFilter(CAN_READ,
CanWriteFileFilter.CANNOT_WRITE);
/**
* Restrictive consructor.
*/
protected CanReadFileFilter() {
}
/**
* Checks to see if the file can be read.
*
* @param file the File to check.
* @return <code>true</code> if the file can be
* read, otherwise <code>false</code>.
*/
public boolean accept(File file) {
return file.canRead();
}
}

View File

@ -1,80 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
/**
* This filter accepts <code>File</code>s that can be written to.
* <p>
* Example, showing how to print out a list of the
* current directory's <i>writable</i> files:
*
* <pre>
* File dir = new File(".");
* String[] files = dir.list( CanWriteFileFilter.CAN_WRITE );
* for ( int i = 0; i &lt; files.length; i++ ) {
* System.out.println(files[i]);
* }
* </pre>
*
* <p>
* Example, showing how to print out a list of the
* current directory's <i>un-writable</i> files:
*
* <pre>
* File dir = new File(".");
* String[] files = dir.list( CanWriteFileFilter.CANNOT_WRITE );
* for ( int i = 0; i &lt; files.length; i++ ) {
* System.out.println(files[i]);
* }
* </pre>
*
* <p>
* <b>N.B.</b> For read-only files, use
* <code>CanReadFileFilter.READ_ONLY</code>.
*
* @since Commons IO 1.3
* @version $Revision: 587916 $
*/
public class CanWriteFileFilter extends AbstractFileFilter implements Serializable {
/** Singleton instance of <i>writable</i> filter */
public static final IOFileFilter CAN_WRITE = new CanWriteFileFilter();
/** Singleton instance of not <i>writable</i> filter */
public static final IOFileFilter CANNOT_WRITE = new NotFileFilter(CAN_WRITE);
/**
* Restrictive consructor.
*/
protected CanWriteFileFilter() {
}
/**
* Checks to see if the file can be written to.
*
* @param file the File to check
* @return <code>true</code> if the file can be
* written to, otherwise <code>false</code>.
*/
public boolean accept(File file) {
return file.canWrite();
}
}

View File

@ -1,67 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.util.List;
/**
* Defines operations for conditional file filters.
*
* @since Commons IO 1.1
* @version $Revision: 437567 $ $Date: 2006-08-28 07:39:07 +0100 (Mon, 28 Aug 2006) $
*
* @author Steven Caswell
*/
public interface ConditionalFileFilter {
/**
* Adds the specified file filter to the list of file filters at the end of
* the list.
*
* @param ioFileFilter the filter to be added
* @since Commons IO 1.1
*/
public void addFileFilter(IOFileFilter ioFileFilter);
/**
* Returns this conditional file filter's list of file filters.
*
* @return the file filter list
* @since Commons IO 1.1
*/
public List getFileFilters();
/**
* Removes the specified file filter.
*
* @param ioFileFilter filter to be removed
* @return <code>true</code> if the filter was found in the list,
* <code>false</code> otherwise
* @since Commons IO 1.1
*/
public boolean removeFileFilter(IOFileFilter ioFileFilter);
/**
* Sets the list of file filters, replacing any previously configured
* file filters on this filter.
*
* @param fileFilters the list of filters
* @since Commons IO 1.1
*/
public void setFileFilters(List fileFilters);
}

View File

@ -1,104 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.Serializable;
/**
* This class turns a Java FileFilter or FilenameFilter into an IO FileFilter.
*
* @since Commons IO 1.0
* @version $Revision: 591058 $ $Date: 2007-11-01 15:47:05 +0000 (Thu, 01 Nov 2007) $
*
* @author Stephen Colebourne
*/
public class DelegateFileFilter extends AbstractFileFilter implements Serializable {
/** The Filename filter */
private final FilenameFilter filenameFilter;
/** The File filter */
private final FileFilter fileFilter;
/**
* Constructs a delegate file filter around an existing FilenameFilter.
*
* @param filter the filter to decorate
*/
public DelegateFileFilter(FilenameFilter filter) {
if (filter == null) {
throw new IllegalArgumentException("The FilenameFilter must not be null");
}
this.filenameFilter = filter;
this.fileFilter = null;
}
/**
* Constructs a delegate file filter around an existing FileFilter.
*
* @param filter the filter to decorate
*/
public DelegateFileFilter(FileFilter filter) {
if (filter == null) {
throw new IllegalArgumentException("The FileFilter must not be null");
}
this.fileFilter = filter;
this.filenameFilter = null;
}
/**
* Checks the filter.
*
* @param file the file to check
* @return true if the filter matches
*/
public boolean accept(File file) {
if (fileFilter != null) {
return fileFilter.accept(file);
} else {
return super.accept(file);
}
}
/**
* Checks the filter.
*
* @param dir the directory
* @param name the filename in the directory
* @return true if the filter matches
*/
public boolean accept(File dir, String name) {
if (filenameFilter != null) {
return filenameFilter.accept(dir, name);
} else {
return super.accept(dir, name);
}
}
/**
* Provide a String representaion of this file filter.
*
* @return a String representaion
*/
public String toString() {
String delegate = (fileFilter != null ? fileFilter.toString() : filenameFilter.toString());
return super.toString() + "(" + delegate + ")";
}
}

View File

@ -1,73 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
/**
* This filter accepts <code>File</code>s that are directories.
* <p>
* For example, here is how to print out a list of the
* current directory's subdirectories:
*
* <pre>
* File dir = new File(".");
* String[] files = dir.list( DirectoryFileFilter.INSTANCE );
* for ( int i = 0; i &lt; files.length; i++ ) {
* System.out.println(files[i]);
* }
* </pre>
*
* @since Commons IO 1.0
* @version $Revision: 587916 $ $Date: 2007-10-24 16:53:07 +0100 (Wed, 24 Oct 2007) $
*
* @author Stephen Colebourne
* @author Peter Donald
*/
public class DirectoryFileFilter extends AbstractFileFilter implements Serializable {
/**
* Singleton instance of directory filter.
* @since Commons IO 1.3
*/
public static final IOFileFilter DIRECTORY = new DirectoryFileFilter();
/**
* Singleton instance of directory filter.
* Please use the identical DirectoryFileFilter.DIRECTORY constant.
* The new name is more JDK 1.5 friendly as it doesn't clash with other
* values when using static imports.
*/
public static final IOFileFilter INSTANCE = DIRECTORY;
/**
* Restrictive consructor.
*/
protected DirectoryFileFilter() {
}
/**
* Checks to see if the file is a directory.
*
* @param file the File to check
* @return true if the file is a directory
*/
public boolean accept(File file) {
return file.isDirectory();
}
}

View File

@ -1,84 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
/**
* This filter accepts files or directories that are empty.
* <p>
* If the <code>File</code> is a directory it checks that
* it contains no files.
* <p>
* Example, showing how to print out a list of the
* current directory's empty files/directories:
*
* <pre>
* File dir = new File(".");
* String[] files = dir.list( EmptyFileFilter.EMPTY );
* for ( int i = 0; i &lt; files.length; i++ ) {
* System.out.println(files[i]);
* }
* </pre>
*
* <p>
* Example, showing how to print out a list of the
* current directory's non-empty files/directories:
*
* <pre>
* File dir = new File(".");
* String[] files = dir.list( EmptyFileFilter.NOT_EMPTY );
* for ( int i = 0; i &lt; files.length; i++ ) {
* System.out.println(files[i]);
* }
* </pre>
*
* @since Commons IO 1.3
* @version $Revision: 587916 $
*/
public class EmptyFileFilter extends AbstractFileFilter implements Serializable {
/** Singleton instance of <i>empty</i> filter */
public static final IOFileFilter EMPTY = new EmptyFileFilter();
/** Singleton instance of <i>not-empty</i> filter */
public static final IOFileFilter NOT_EMPTY = new NotFileFilter(EMPTY);
/**
* Restrictive consructor.
*/
protected EmptyFileFilter() {
}
/**
* Checks to see if the file is empty.
*
* @param file the file or directory to check
* @return <code>true</code> if the file or directory
* is <i>empty</i>, otherwise <code>false</code>.
*/
public boolean accept(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
return (files == null || files.length == 0);
} else {
return (file.length() == 0);
}
}
}

View File

@ -1,72 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
/**
* A file filter that always returns false.
*
* @since Commons IO 1.0
* @version $Revision: 587978 $ $Date: 2007-10-24 20:36:51 +0100 (Wed, 24 Oct 2007) $
*
* @author Stephen Colebourne
*/
public class FalseFileFilter implements IOFileFilter, Serializable {
/**
* Singleton instance of false filter.
* @since Commons IO 1.3
*/
public static final IOFileFilter FALSE = new FalseFileFilter();
/**
* Singleton instance of false filter.
* Please use the identical FalseFileFilter.FALSE constant.
* The new name is more JDK 1.5 friendly as it doesn't clash with other
* values when using static imports.
*/
public static final IOFileFilter INSTANCE = FALSE;
/**
* Restrictive consructor.
*/
protected FalseFileFilter() {
}
/**
* Returns false.
*
* @param file the file to check
* @return false
*/
public boolean accept(File file) {
return false;
}
/**
* Returns false.
*
* @param dir the directory to check
* @param name the filename
* @return false
*/
public boolean accept(File dir, String name) {
return false;
}
}

View File

@ -1,60 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
/**
* This filter accepts <code>File</code>s that are files (not directories).
* <p>
* For example, here is how to print out a list of the real files
* within the current directory:
*
* <pre>
* File dir = new File(".");
* String[] files = dir.list( FileFileFilter.FILE );
* for ( int i = 0; i &lt; files.length; i++ ) {
* System.out.println(files[i]);
* }
* </pre>
*
* @since Commons IO 1.3
* @version $Revision: 155419 $ $Date: 2007-10-24 16:53:07 +0100 (Wed, 24 Oct 2007) $
*/
public class FileFileFilter extends AbstractFileFilter implements Serializable {
/** Singleton instance of file filter */
public static final IOFileFilter FILE = new FileFileFilter();
/**
* Restrictive consructor.
*/
protected FileFileFilter() {
}
/**
* Checks to see if the file is a file.
*
* @param file the File to check
* @return true if the file is a file
*/
public boolean accept(File file) {
return file.isFile();
}
}

View File

@ -1,361 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.util.Date;
/**
* Useful utilities for working with file filters. It provides access to all
* file filter implementations in this package so you don't have to import
* every class you use.
*
* @since Commons IO 1.0
* @version $Id: FileFilterUtils.java 609286 2008-01-06 10:01:26Z scolebourne $
*
* @author Stephen Colebourne
* @author Jeremias Maerki
* @author Masato Tezuka
* @author Rahul Akolkar
*/
public class FileFilterUtils {
/**
* FileFilterUtils is not normally instantiated.
*/
public FileFilterUtils() {
}
//-----------------------------------------------------------------------
/**
* Returns a filter that returns true if the filename starts with the specified text.
*
* @param prefix the filename prefix
* @return a prefix checking filter
*/
public static IOFileFilter prefixFileFilter(String prefix) {
return new PrefixFileFilter(prefix);
}
/**
* Returns a filter that returns true if the filename ends with the specified text.
*
* @param suffix the filename suffix
* @return a suffix checking filter
*/
public static IOFileFilter suffixFileFilter(String suffix) {
return new SuffixFileFilter(suffix);
}
/**
* Returns a filter that returns true if the filename matches the specified text.
*
* @param name the filename
* @return a name checking filter
*/
public static IOFileFilter nameFileFilter(String name) {
return new NameFileFilter(name);
}
/**
* Returns a filter that checks if the file is a directory.
*
* @return file filter that accepts only directories and not files
*/
public static IOFileFilter directoryFileFilter() {
return DirectoryFileFilter.DIRECTORY;
}
/**
* Returns a filter that checks if the file is a file (and not a directory).
*
* @return file filter that accepts only files and not directories
*/
public static IOFileFilter fileFileFilter() {
return FileFileFilter.FILE;
}
//-----------------------------------------------------------------------
/**
* Returns a filter that ANDs the two specified filters.
*
* @param filter1 the first filter
* @param filter2 the second filter
* @return a filter that ANDs the two specified filters
*/
public static IOFileFilter andFileFilter(IOFileFilter filter1, IOFileFilter filter2) {
return new AndFileFilter(filter1, filter2);
}
/**
* Returns a filter that ORs the two specified filters.
*
* @param filter1 the first filter
* @param filter2 the second filter
* @return a filter that ORs the two specified filters
*/
public static IOFileFilter orFileFilter(IOFileFilter filter1, IOFileFilter filter2) {
return new OrFileFilter(filter1, filter2);
}
/**
* Returns a filter that NOTs the specified filter.
*
* @param filter the filter to invert
* @return a filter that NOTs the specified filter
*/
public static IOFileFilter notFileFilter(IOFileFilter filter) {
return new NotFileFilter(filter);
}
//-----------------------------------------------------------------------
/**
* Returns a filter that always returns true.
*
* @return a true filter
*/
public static IOFileFilter trueFileFilter() {
return TrueFileFilter.TRUE;
}
/**
* Returns a filter that always returns false.
*
* @return a false filter
*/
public static IOFileFilter falseFileFilter() {
return FalseFileFilter.FALSE;
}
//-----------------------------------------------------------------------
/**
* Returns an <code>IOFileFilter</code> that wraps the
* <code>FileFilter</code> instance.
*
* @param filter the filter to be wrapped
* @return a new filter that implements IOFileFilter
*/
public static IOFileFilter asFileFilter(FileFilter filter) {
return new DelegateFileFilter(filter);
}
/**
* Returns an <code>IOFileFilter</code> that wraps the
* <code>FilenameFilter</code> instance.
*
* @param filter the filter to be wrapped
* @return a new filter that implements IOFileFilter
*/
public static IOFileFilter asFileFilter(FilenameFilter filter) {
return new DelegateFileFilter(filter);
}
//-----------------------------------------------------------------------
/**
* Returns a filter that returns true if the file was last modified after
* the specified cutoff time.
*
* @param cutoff the time threshold
* @return an appropriately configured age file filter
* @since Commons IO 1.2
*/
public static IOFileFilter ageFileFilter(long cutoff) {
return new AgeFileFilter(cutoff);
}
/**
* Returns a filter that filters files based on a cutoff time.
*
* @param cutoff the time threshold
* @param acceptOlder if true, older files get accepted, if false, newer
* @return an appropriately configured age file filter
* @since Commons IO 1.2
*/
public static IOFileFilter ageFileFilter(long cutoff, boolean acceptOlder) {
return new AgeFileFilter(cutoff, acceptOlder);
}
/**
* Returns a filter that returns true if the file was last modified after
* the specified cutoff date.
*
* @param cutoffDate the time threshold
* @return an appropriately configured age file filter
* @since Commons IO 1.2
*/
public static IOFileFilter ageFileFilter(Date cutoffDate) {
return new AgeFileFilter(cutoffDate);
}
/**
* Returns a filter that filters files based on a cutoff date.
*
* @param cutoffDate the time threshold
* @param acceptOlder if true, older files get accepted, if false, newer
* @return an appropriately configured age file filter
* @since Commons IO 1.2
*/
public static IOFileFilter ageFileFilter(Date cutoffDate, boolean acceptOlder) {
return new AgeFileFilter(cutoffDate, acceptOlder);
}
/**
* Returns a filter that returns true if the file was last modified after
* the specified reference file.
*
* @param cutoffReference the file whose last modification
* time is usesd as the threshold age of the files
* @return an appropriately configured age file filter
* @since Commons IO 1.2
*/
public static IOFileFilter ageFileFilter(File cutoffReference) {
return new AgeFileFilter(cutoffReference);
}
/**
* Returns a filter that filters files based on a cutoff reference file.
*
* @param cutoffReference the file whose last modification
* time is usesd as the threshold age of the files
* @param acceptOlder if true, older files get accepted, if false, newer
* @return an appropriately configured age file filter
* @since Commons IO 1.2
*/
public static IOFileFilter ageFileFilter(File cutoffReference, boolean acceptOlder) {
return new AgeFileFilter(cutoffReference, acceptOlder);
}
//-----------------------------------------------------------------------
/**
* Returns a filter that returns true if the file is bigger than a certain size.
*
* @param threshold the file size threshold
* @return an appropriately configured SizeFileFilter
* @since Commons IO 1.2
*/
public static IOFileFilter sizeFileFilter(long threshold) {
return new SizeFileFilter(threshold);
}
/**
* Returns a filter that filters based on file size.
*
* @param threshold the file size threshold
* @param acceptLarger if true, larger files get accepted, if false, smaller
* @return an appropriately configured SizeFileFilter
* @since Commons IO 1.2
*/
public static IOFileFilter sizeFileFilter(long threshold, boolean acceptLarger) {
return new SizeFileFilter(threshold, acceptLarger);
}
/**
* Returns a filter that accepts files whose size is &gt;= minimum size
* and &lt;= maximum size.
*
* @param minSizeInclusive the minimum file size (inclusive)
* @param maxSizeInclusive the maximum file size (inclusive)
* @return an appropriately configured IOFileFilter
* @since Commons IO 1.3
*/
public static IOFileFilter sizeRangeFileFilter(long minSizeInclusive, long maxSizeInclusive ) {
IOFileFilter minimumFilter = new SizeFileFilter(minSizeInclusive, true);
IOFileFilter maximumFilter = new SizeFileFilter(maxSizeInclusive + 1L, false);
return new AndFileFilter(minimumFilter, maximumFilter);
}
//-----------------------------------------------------------------------
/* Constructed on demand and then cached */
private static IOFileFilter cvsFilter;
/* Constructed on demand and then cached */
private static IOFileFilter svnFilter;
/**
* Decorates a filter to make it ignore CVS directories.
* Passing in <code>null</code> will return a filter that accepts everything
* except CVS directories.
*
* @param filter the filter to decorate, null means an unrestricted filter
* @return the decorated filter, never null
* @since Commons IO 1.1 (method existed but had bug in 1.0)
*/
public static IOFileFilter makeCVSAware(IOFileFilter filter) {
if (cvsFilter == null) {
cvsFilter = notFileFilter(
andFileFilter(directoryFileFilter(), nameFileFilter("CVS")));
}
if (filter == null) {
return cvsFilter;
} else {
return andFileFilter(filter, cvsFilter);
}
}
/**
* Decorates a filter to make it ignore SVN directories.
* Passing in <code>null</code> will return a filter that accepts everything
* except SVN directories.
*
* @param filter the filter to decorate, null means an unrestricted filter
* @return the decorated filter, never null
* @since Commons IO 1.1
*/
public static IOFileFilter makeSVNAware(IOFileFilter filter) {
if (svnFilter == null) {
svnFilter = notFileFilter(
andFileFilter(directoryFileFilter(), nameFileFilter(".svn")));
}
if (filter == null) {
return svnFilter;
} else {
return andFileFilter(filter, svnFilter);
}
}
//-----------------------------------------------------------------------
/**
* Decorates a filter so that it only applies to directories and not to files.
*
* @param filter the filter to decorate, null means an unrestricted filter
* @return the decorated filter, never null
* @since Commons IO 1.3
*/
public static IOFileFilter makeDirectoryOnly(IOFileFilter filter) {
if (filter == null) {
return DirectoryFileFilter.DIRECTORY;
}
return new AndFileFilter(DirectoryFileFilter.DIRECTORY, filter);
}
/**
* Decorates a filter so that it only applies to files and not to directories.
*
* @param filter the filter to decorate, null means an unrestricted filter
* @return the decorated filter, never null
* @since Commons IO 1.3
*/
public static IOFileFilter makeFileOnly(IOFileFilter filter) {
if (filter == null) {
return FileFileFilter.FILE;
}
return new AndFileFilter(FileFileFilter.FILE, filter);
}
}

View File

@ -1,76 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
/**
* This filter accepts <code>File</code>s that are hidden.
* <p>
* Example, showing how to print out a list of the
* current directory's <i>hidden</i> files:
*
* <pre>
* File dir = new File(".");
* String[] files = dir.list( HiddenFileFilter.HIDDEN );
* for ( int i = 0; i &lt; files.length; i++ ) {
* System.out.println(files[i]);
* }
* </pre>
*
* <p>
* Example, showing how to print out a list of the
* current directory's <i>visible</i> (i.e. not hidden) files:
*
* <pre>
* File dir = new File(".");
* String[] files = dir.list( HiddenFileFilter.VISIBLE );
* for ( int i = 0; i &lt; files.length; i++ ) {
* System.out.println(files[i]);
* }
* </pre>
*
* @since Commons IO 1.3
* @version $Revision: 587916 $
*/
public class HiddenFileFilter extends AbstractFileFilter implements Serializable {
/** Singleton instance of <i>hidden</i> filter */
public static final IOFileFilter HIDDEN = new HiddenFileFilter();
/** Singleton instance of <i>visible</i> filter */
public static final IOFileFilter VISIBLE = new NotFileFilter(HIDDEN);
/**
* Restrictive consructor.
*/
protected HiddenFileFilter() {
}
/**
* Checks to see if the file is hidden.
*
* @param file the File to check
* @return <code>true</code> if the file is
* <i>hidden</i>, otherwise <code>false</code>.
*/
public boolean accept(File file) {
return file.isHidden();
}
}

View File

@ -1,55 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
/**
* An interface which brings the FileFilter and FilenameFilter
* interfaces together.
*
* @since Commons IO 1.0
* @version $Revision: 471628 $ $Date: 2006-11-06 04:06:45 +0000 (Mon, 06 Nov 2006) $
*
* @author Stephen Colebourne
*/
public interface IOFileFilter extends FileFilter, FilenameFilter {
/**
* Checks to see if the File should be accepted by this filter.
* <p>
* Defined in {@link java.io.FileFilter}.
*
* @param file the File to check
* @return true if this file matches the test
*/
public boolean accept(File file);
/**
* Checks to see if the File should be accepted by this filter.
* <p>
* Defined in {@link java.io.FilenameFilter}.
*
* @param dir the directory File to check
* @param name the filename within the directory to check
* @return true if this file matches the test
*/
public boolean accept(File dir, String name);
}

View File

@ -1,191 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.io.IOCase;
/**
* Filters filenames for a certain name.
* <p>
* For example, to print all files and directories in the
* current directory whose name is <code>Test</code>:
*
* <pre>
* File dir = new File(".");
* String[] files = dir.list( new NameFileFilter("Test") );
* for ( int i = 0; i &lt; files.length; i++ ) {
* System.out.println(files[i]);
* }
* </pre>
*
* @since Commons IO 1.0
* @version $Revision: 606381 $ $Date: 2007-12-22 02:03:16 +0000 (Sat, 22 Dec 2007) $
*
* @author Stephen Colebourne
* @author Federico Barbieri
* @author Serge Knystautas
* @author Peter Donald
*/
public class NameFileFilter extends AbstractFileFilter implements Serializable {
/** The filenames to search for */
private final String[] names;
/** Whether the comparison is case sensitive. */
private final IOCase caseSensitivity;
/**
* Constructs a new case-sensitive name file filter for a single name.
*
* @param name the name to allow, must not be null
* @throws IllegalArgumentException if the name is null
*/
public NameFileFilter(String name) {
this(name, null);
}
/**
* Construct a new name file filter specifying case-sensitivity.
*
* @param name the name to allow, must not be null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the name is null
*/
public NameFileFilter(String name, IOCase caseSensitivity) {
if (name == null) {
throw new IllegalArgumentException("The wildcard must not be null");
}
this.names = new String[] {name};
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
/**
* Constructs a new case-sensitive name file filter for an array of names.
* <p>
* The array is not cloned, so could be changed after constructing the
* instance. This would be inadvisable however.
*
* @param names the names to allow, must not be null
* @throws IllegalArgumentException if the names array is null
*/
public NameFileFilter(String[] names) {
this(names, null);
}
/**
* Constructs a new name file filter for an array of names specifying case-sensitivity.
* <p>
* The array is not cloned, so could be changed after constructing the
* instance. This would be inadvisable however.
*
* @param names the names to allow, must not be null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the names array is null
*/
public NameFileFilter(String[] names, IOCase caseSensitivity) {
if (names == null) {
throw new IllegalArgumentException("The array of names must not be null");
}
this.names = names;
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
/**
* Constructs a new case-sensitive name file filter for a list of names.
*
* @param names the names to allow, must not be null
* @throws IllegalArgumentException if the name list is null
* @throws ClassCastException if the list does not contain Strings
*/
public NameFileFilter(List names) {
this(names, null);
}
/**
* Constructs a new name file filter for a list of names specifying case-sensitivity.
*
* @param names the names to allow, must not be null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the name list is null
* @throws ClassCastException if the list does not contain Strings
*/
public NameFileFilter(List names, IOCase caseSensitivity) {
if (names == null) {
throw new IllegalArgumentException("The list of names must not be null");
}
this.names = (String[]) names.toArray(new String[names.size()]);
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
//-----------------------------------------------------------------------
/**
* Checks to see if the filename matches.
*
* @param file the File to check
* @return true if the filename matches
*/
public boolean accept(File file) {
String name = file.getName();
for (int i = 0; i < this.names.length; i++) {
if (caseSensitivity.checkEquals(name, names[i])) {
return true;
}
}
return false;
}
/**
* Checks to see if the filename matches.
*
* @param file the File directory
* @param name the filename
* @return true if the filename matches
*/
public boolean accept(File file, String name) {
for (int i = 0; i < names.length; i++) {
if (caseSensitivity.checkEquals(name, names[i])) {
return true;
}
}
return false;
}
/**
* Provide a String representaion of this file filter.
*
* @return a String representaion
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(super.toString());
buffer.append("(");
if (names != null) {
for (int i = 0; i < names.length; i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(names[i]);
}
}
buffer.append(")");
return buffer.toString();
}
}

View File

@ -1,78 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
/**
* This filter produces a logical NOT of the filters specified.
*
* @since Commons IO 1.0
* @version $Revision: 591058 $ $Date: 2007-11-01 15:47:05 +0000 (Thu, 01 Nov 2007) $
*
* @author Stephen Colebourne
*/
public class NotFileFilter extends AbstractFileFilter implements Serializable {
/** The filter */
private final IOFileFilter filter;
/**
* Constructs a new file filter that NOTs the result of another filters.
*
* @param filter the filter, must not be null
* @throws IllegalArgumentException if the filter is null
*/
public NotFileFilter(IOFileFilter filter) {
if (filter == null) {
throw new IllegalArgumentException("The filter must not be null");
}
this.filter = filter;
}
/**
* Checks to see if both filters are true.
*
* @param file the File to check
* @return true if the filter returns false
*/
public boolean accept(File file) {
return ! filter.accept(file);
}
/**
* Checks to see if both filters are true.
*
* @param file the File directory
* @param name the filename
* @return true if the filter returns false
*/
public boolean accept(File file, String name) {
return ! filter.accept(file, name);
}
/**
* Provide a String representaion of this file filter.
*
* @return a String representaion
*/
public String toString() {
return super.toString() + "(" + filter.toString() + ")";
}
}

View File

@ -1,161 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* A {@link java.io.FileFilter} providing conditional OR logic across a list of
* file filters. This filter returns <code>true</code> if any filters in the
* list return <code>true</code>. Otherwise, it returns <code>false</code>.
* Checking of the file filter list stops when the first filter returns
* <code>true</code>.
*
* @since Commons IO 1.0
* @version $Revision: 606381 $ $Date: 2007-12-22 02:03:16 +0000 (Sat, 22 Dec 2007) $
*
* @author Steven Caswell
*/
public class OrFileFilter
extends AbstractFileFilter
implements ConditionalFileFilter, Serializable {
/** The list of file filters. */
private List fileFilters;
/**
* Constructs a new instance of <code>OrFileFilter</code>.
*
* @since Commons IO 1.1
*/
public OrFileFilter() {
this.fileFilters = new ArrayList();
}
/**
* Constructs a new instance of <code>OrFileFilter</code>
* with the specified filters.
*
* @param fileFilters the file filters for this filter, copied, null ignored
* @since Commons IO 1.1
*/
public OrFileFilter(final List fileFilters) {
if (fileFilters == null) {
this.fileFilters = new ArrayList();
} else {
this.fileFilters = new ArrayList(fileFilters);
}
}
/**
* Constructs a new file filter that ORs the result of two other filters.
*
* @param filter1 the first filter, must not be null
* @param filter2 the second filter, must not be null
* @throws IllegalArgumentException if either filter is null
*/
public OrFileFilter(IOFileFilter filter1, IOFileFilter filter2) {
if (filter1 == null || filter2 == null) {
throw new IllegalArgumentException("The filters must not be null");
}
this.fileFilters = new ArrayList();
addFileFilter(filter1);
addFileFilter(filter2);
}
/**
* {@inheritDoc}
*/
public void addFileFilter(final IOFileFilter ioFileFilter) {
this.fileFilters.add(ioFileFilter);
}
/**
* {@inheritDoc}
*/
public List getFileFilters() {
return Collections.unmodifiableList(this.fileFilters);
}
/**
* {@inheritDoc}
*/
public boolean removeFileFilter(IOFileFilter ioFileFilter) {
return this.fileFilters.remove(ioFileFilter);
}
/**
* {@inheritDoc}
*/
public void setFileFilters(final List fileFilters) {
this.fileFilters = fileFilters;
}
/**
* {@inheritDoc}
*/
public boolean accept(final File file) {
for (Iterator iter = this.fileFilters.iterator(); iter.hasNext();) {
IOFileFilter fileFilter = (IOFileFilter) iter.next();
if (fileFilter.accept(file)) {
return true;
}
}
return false;
}
/**
* {@inheritDoc}
*/
public boolean accept(final File file, final String name) {
for (Iterator iter = this.fileFilters.iterator(); iter.hasNext();) {
IOFileFilter fileFilter = (IOFileFilter) iter.next();
if (fileFilter.accept(file, name)) {
return true;
}
}
return false;
}
/**
* Provide a String representaion of this file filter.
*
* @return a String representaion
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(super.toString());
buffer.append("(");
if (fileFilters != null) {
for (int i = 0; i < fileFilters.size(); i++) {
if (i > 0) {
buffer.append(",");
}
Object filter = fileFilters.get(i);
buffer.append(filter == null ? "null" : filter.toString());
}
}
buffer.append(")");
return buffer.toString();
}
}

View File

@ -1,197 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.io.IOCase;
/**
* Filters filenames for a certain prefix.
* <p>
* For example, to print all files and directories in the
* current directory whose name starts with <code>Test</code>:
*
* <pre>
* File dir = new File(".");
* String[] files = dir.list( new PrefixFileFilter("Test") );
* for ( int i = 0; i &lt; files.length; i++ ) {
* System.out.println(files[i]);
* }
* </pre>
*
* @since Commons IO 1.0
* @version $Revision: 606381 $ $Date: 2007-12-22 02:03:16 +0000 (Sat, 22 Dec 2007) $
*
* @author Stephen Colebourne
* @author Federico Barbieri
* @author Serge Knystautas
* @author Peter Donald
*/
public class PrefixFileFilter extends AbstractFileFilter implements Serializable {
/** The filename prefixes to search for */
private final String[] prefixes;
/** Whether the comparison is case sensitive. */
private final IOCase caseSensitivity;
/**
* Constructs a new Prefix file filter for a single prefix.
*
* @param prefix the prefix to allow, must not be null
* @throws IllegalArgumentException if the prefix is null
*/
public PrefixFileFilter(String prefix) {
this(prefix, IOCase.SENSITIVE);
}
/**
* Constructs a new Prefix file filter for a single prefix
* specifying case-sensitivity.
*
* @param prefix the prefix to allow, must not be null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the prefix is null
* @since Commons IO 1.4
*/
public PrefixFileFilter(String prefix, IOCase caseSensitivity) {
if (prefix == null) {
throw new IllegalArgumentException("The prefix must not be null");
}
this.prefixes = new String[] {prefix};
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
/**
* Constructs a new Prefix file filter for any of an array of prefixes.
* <p>
* The array is not cloned, so could be changed after constructing the
* instance. This would be inadvisable however.
*
* @param prefixes the prefixes to allow, must not be null
* @throws IllegalArgumentException if the prefix array is null
*/
public PrefixFileFilter(String[] prefixes) {
this(prefixes, IOCase.SENSITIVE);
}
/**
* Constructs a new Prefix file filter for any of an array of prefixes
* specifying case-sensitivity.
* <p>
* The array is not cloned, so could be changed after constructing the
* instance. This would be inadvisable however.
*
* @param prefixes the prefixes to allow, must not be null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the prefix is null
* @since Commons IO 1.4
*/
public PrefixFileFilter(String[] prefixes, IOCase caseSensitivity) {
if (prefixes == null) {
throw new IllegalArgumentException("The array of prefixes must not be null");
}
this.prefixes = prefixes;
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
/**
* Constructs a new Prefix file filter for a list of prefixes.
*
* @param prefixes the prefixes to allow, must not be null
* @throws IllegalArgumentException if the prefix list is null
* @throws ClassCastException if the list does not contain Strings
*/
public PrefixFileFilter(List prefixes) {
this(prefixes, IOCase.SENSITIVE);
}
/**
* Constructs a new Prefix file filter for a list of prefixes
* specifying case-sensitivity.
*
* @param prefixes the prefixes to allow, must not be null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the prefix list is null
* @throws ClassCastException if the list does not contain Strings
* @since Commons IO 1.4
*/
public PrefixFileFilter(List prefixes, IOCase caseSensitivity) {
if (prefixes == null) {
throw new IllegalArgumentException("The list of prefixes must not be null");
}
this.prefixes = (String[]) prefixes.toArray(new String[prefixes.size()]);
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
/**
* Checks to see if the filename starts with the prefix.
*
* @param file the File to check
* @return true if the filename starts with one of our prefixes
*/
public boolean accept(File file) {
String name = file.getName();
for (int i = 0; i < this.prefixes.length; i++) {
if (caseSensitivity.checkStartsWith(name, prefixes[i])) {
return true;
}
}
return false;
}
/**
* Checks to see if the filename starts with the prefix.
*
* @param file the File directory
* @param name the filename
* @return true if the filename starts with one of our prefixes
*/
public boolean accept(File file, String name) {
for (int i = 0; i < prefixes.length; i++) {
if (caseSensitivity.checkStartsWith(name, prefixes[i])) {
return true;
}
}
return false;
}
/**
* Provide a String representaion of this file filter.
*
* @return a String representaion
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(super.toString());
buffer.append("(");
if (prefixes != null) {
for (int i = 0; i < prefixes.length; i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(prefixes[i]);
}
}
buffer.append(")");
return buffer.toString();
}
}

View File

@ -1,122 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.regex.Pattern;
import org.apache.commons.io.IOCase;
/**
* Filters files using supplied regular expression(s).
* <p/>
* See java.util.regex.Pattern for regex matching rules
* <p/>
*
* <p/>
* e.g.
* <pre>
* File dir = new File(".");
* FileFilter fileFilter = new RegexFileFilter("^.*[tT]est(-\\d+)?\\.java$");
* File[] files = dir.listFiles(fileFilter);
* for (int i = 0; i < files.length; i++) {
* System.out.println(files[i]);
* }
* </pre>
*
* @author Oliver Siegmar
* @version $Revision: 606381 $
* @since Commons IO 1.4
*/
public class RegexFileFilter extends AbstractFileFilter implements Serializable {
/** The regular expression pattern that will be used to match filenames */
private final Pattern pattern;
/**
* Construct a new regular expression filter.
*
* @param pattern regular string expression to match
* @throws IllegalArgumentException if the pattern is null
*/
public RegexFileFilter(String pattern) {
if (pattern == null) {
throw new IllegalArgumentException("Pattern is missing");
}
this.pattern = Pattern.compile(pattern);
}
/**
* Construct a new regular expression filter with the specified flags case sensitivity.
*
* @param pattern regular string expression to match
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the pattern is null
*/
public RegexFileFilter(String pattern, IOCase caseSensitivity) {
if (pattern == null) {
throw new IllegalArgumentException("Pattern is missing");
}
int flags = 0;
if (caseSensitivity != null && !caseSensitivity.isCaseSensitive()) {
flags = Pattern.CASE_INSENSITIVE;
}
this.pattern = Pattern.compile(pattern, flags);
}
/**
* Construct a new regular expression filter with the specified flags.
*
* @param pattern regular string expression to match
* @param flags pattern flags - e.g. {@link Pattern#CASE_INSENSITIVE}
* @throws IllegalArgumentException if the pattern is null
*/
public RegexFileFilter(String pattern, int flags) {
if (pattern == null) {
throw new IllegalArgumentException("Pattern is missing");
}
this.pattern = Pattern.compile(pattern, flags);
}
/**
* Construct a new regular expression filter for a compiled regular expression
*
* @param pattern regular expression to match
* @throws IllegalArgumentException if the pattern is null
*/
public RegexFileFilter(Pattern pattern) {
if (pattern == null) {
throw new IllegalArgumentException("Pattern is missing");
}
this.pattern = pattern;
}
/**
* Checks to see if the filename matches one of the regular expressions.
*
* @param dir the file directory
* @param name the filename
* @return true if the filename matches one of the regular expressions
*/
public boolean accept(File dir, String name) {
return (pattern.matcher(name).matches());
}
}

View File

@ -1,103 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
/**
* Filters files based on size, can filter either smaller files or
* files equal to or larger than a given threshold.
* <p>
* For example, to print all files and directories in the
* current directory whose size is greater than 1 MB:
*
* <pre>
* File dir = new File(".");
* String[] files = dir.list( new SizeFileFilter(1024 * 1024) );
* for ( int i = 0; i &lt; files.length; i++ ) {
* System.out.println(files[i]);
* }
* </pre>
*
* @author Rahul Akolkar
* @version $Id: SizeFileFilter.java 591058 2007-11-01 15:47:05Z niallp $
* @since Commons IO 1.2
*/
public class SizeFileFilter extends AbstractFileFilter implements Serializable {
/** The size threshold. */
private final long size;
/** Whether the files accepted will be larger or smaller. */
private final boolean acceptLarger;
/**
* Constructs a new size file filter for files equal to or
* larger than a certain size.
*
* @param size the threshold size of the files
* @throws IllegalArgumentException if the size is negative
*/
public SizeFileFilter(long size) {
this(size, true);
}
/**
* Constructs a new size file filter for files based on a certain size
* threshold.
*
* @param size the threshold size of the files
* @param acceptLarger if true, files equal to or larger are accepted,
* otherwise smaller ones (but not equal to)
* @throws IllegalArgumentException if the size is negative
*/
public SizeFileFilter(long size, boolean acceptLarger) {
if (size < 0) {
throw new IllegalArgumentException("The size must be non-negative");
}
this.size = size;
this.acceptLarger = acceptLarger;
}
//-----------------------------------------------------------------------
/**
* Checks to see if the size of the file is favorable.
* <p>
* If size equals threshold and smaller files are required,
* file <b>IS NOT</b> selected.
* If size equals threshold and larger files are required,
* file <b>IS</b> selected.
*
* @param file the File to check
* @return true if the filename matches
*/
public boolean accept(File file) {
boolean smaller = file.length() < size;
return acceptLarger ? !smaller : smaller;
}
/**
* Provide a String representaion of this file filter.
*
* @return a String representaion
*/
public String toString() {
String condition = acceptLarger ? ">=" : "<";
return super.toString() + "(" + condition + size + ")";
}
}

View File

@ -1,198 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.io.IOCase;
/**
* Filters files based on the suffix (what the filename ends with).
* This is used in retrieving all the files of a particular type.
* <p>
* For example, to retrieve and print all <code>*.java</code> files
* in the current directory:
*
* <pre>
* File dir = new File(".");
* String[] files = dir.list( new SuffixFileFilter(".java") );
* for (int i = 0; i &lt; files.length; i++) {
* System.out.println(files[i]);
* }
* </pre>
*
* @since Commons IO 1.0
* @version $Revision: 606381 $ $Date: 2007-12-22 02:03:16 +0000 (Sat, 22 Dec 2007) $
*
* @author Stephen Colebourne
* @author Federico Barbieri
* @author Serge Knystautas
* @author Peter Donald
*/
public class SuffixFileFilter extends AbstractFileFilter implements Serializable {
/** The filename suffixes to search for */
private final String[] suffixes;
/** Whether the comparison is case sensitive. */
private final IOCase caseSensitivity;
/**
* Constructs a new Suffix file filter for a single extension.
*
* @param suffix the suffix to allow, must not be null
* @throws IllegalArgumentException if the suffix is null
*/
public SuffixFileFilter(String suffix) {
this(suffix, IOCase.SENSITIVE);
}
/**
* Constructs a new Suffix file filter for a single extension
* specifying case-sensitivity.
*
* @param suffix the suffix to allow, must not be null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the suffix is null
* @since Commons IO 1.4
*/
public SuffixFileFilter(String suffix, IOCase caseSensitivity) {
if (suffix == null) {
throw new IllegalArgumentException("The suffix must not be null");
}
this.suffixes = new String[] {suffix};
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
/**
* Constructs a new Suffix file filter for an array of suffixs.
* <p>
* The array is not cloned, so could be changed after constructing the
* instance. This would be inadvisable however.
*
* @param suffixes the suffixes to allow, must not be null
* @throws IllegalArgumentException if the suffix array is null
*/
public SuffixFileFilter(String[] suffixes) {
this(suffixes, IOCase.SENSITIVE);
}
/**
* Constructs a new Suffix file filter for an array of suffixs
* specifying case-sensitivity.
* <p>
* The array is not cloned, so could be changed after constructing the
* instance. This would be inadvisable however.
*
* @param suffixes the suffixes to allow, must not be null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the suffix array is null
* @since Commons IO 1.4
*/
public SuffixFileFilter(String[] suffixes, IOCase caseSensitivity) {
if (suffixes == null) {
throw new IllegalArgumentException("The array of suffixes must not be null");
}
this.suffixes = suffixes;
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
/**
* Constructs a new Suffix file filter for a list of suffixes.
*
* @param suffixes the suffixes to allow, must not be null
* @throws IllegalArgumentException if the suffix list is null
* @throws ClassCastException if the list does not contain Strings
*/
public SuffixFileFilter(List suffixes) {
this(suffixes, IOCase.SENSITIVE);
}
/**
* Constructs a new Suffix file filter for a list of suffixes
* specifying case-sensitivity.
*
* @param suffixes the suffixes to allow, must not be null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the suffix list is null
* @throws ClassCastException if the list does not contain Strings
* @since Commons IO 1.4
*/
public SuffixFileFilter(List suffixes, IOCase caseSensitivity) {
if (suffixes == null) {
throw new IllegalArgumentException("The list of suffixes must not be null");
}
this.suffixes = (String[]) suffixes.toArray(new String[suffixes.size()]);
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
/**
* Checks to see if the filename ends with the suffix.
*
* @param file the File to check
* @return true if the filename ends with one of our suffixes
*/
public boolean accept(File file) {
String name = file.getName();
for (int i = 0; i < this.suffixes.length; i++) {
if (caseSensitivity.checkEndsWith(name, suffixes[i])) {
return true;
}
}
return false;
}
/**
* Checks to see if the filename ends with the suffix.
*
* @param file the File directory
* @param name the filename
* @return true if the filename ends with one of our suffixes
*/
public boolean accept(File file, String name) {
for (int i = 0; i < this.suffixes.length; i++) {
if (caseSensitivity.checkEndsWith(name, suffixes[i])) {
return true;
}
}
return false;
}
/**
* Provide a String representaion of this file filter.
*
* @return a String representaion
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(super.toString());
buffer.append("(");
if (suffixes != null) {
for (int i = 0; i < suffixes.length; i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(suffixes[i]);
}
}
buffer.append(")");
return buffer.toString();
}
}

View File

@ -1,72 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
/**
* A file filter that always returns true.
*
* @since Commons IO 1.0
* @version $Revision: 587978 $ $Date: 2007-10-24 20:36:51 +0100 (Wed, 24 Oct 2007) $
*
* @author Stephen Colebourne
*/
public class TrueFileFilter implements IOFileFilter, Serializable {
/**
* Singleton instance of true filter.
* @since Commons IO 1.3
*/
public static final IOFileFilter TRUE = new TrueFileFilter();
/**
* Singleton instance of true filter.
* Please use the identical TrueFileFilter.TRUE constant.
* The new name is more JDK 1.5 friendly as it doesn't clash with other
* values when using static imports.
*/
public static final IOFileFilter INSTANCE = TRUE;
/**
* Restrictive consructor.
*/
protected TrueFileFilter() {
}
/**
* Returns true.
*
* @param file the file to check
* @return true
*/
public boolean accept(File file) {
return true;
}
/**
* Returns true.
*
* @param dir the directory to check
* @param name the filename
* @return true
*/
public boolean accept(File dir, String name) {
return true;
}
}

View File

@ -1,196 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOCase;
/**
* Filters files using the supplied wildcards.
* <p>
* This filter selects files and directories based on one or more wildcards.
* Testing is case-sensitive by default, but this can be configured.
* <p>
* The wildcard matcher uses the characters '?' and '*' to represent a
* single or multiple wildcard characters.
* This is the same as often found on Dos/Unix command lines.
* The extension check is case-sensitive by .
* See {@link FilenameUtils#wildcardMatchOnSystem} for more information.
* <p>
* For example:
* <pre>
* File dir = new File(".");
* FileFilter fileFilter = new WildcardFileFilter("*test*.java~*~");
* File[] files = dir.listFiles(fileFilter);
* for (int i = 0; i < files.length; i++) {
* System.out.println(files[i]);
* }
* </pre>
*
* @author Jason Anderson
* @version $Revision: 155419 $ $Date: 2007-12-22 02:03:16 +0000 (Sat, 22 Dec 2007) $
* @since Commons IO 1.3
*/
public class WildcardFileFilter extends AbstractFileFilter implements Serializable {
/** The wildcards that will be used to match filenames. */
private final String[] wildcards;
/** Whether the comparison is case sensitive. */
private final IOCase caseSensitivity;
/**
* Construct a new case-sensitive wildcard filter for a single wildcard.
*
* @param wildcard the wildcard to match
* @throws IllegalArgumentException if the pattern is null
*/
public WildcardFileFilter(String wildcard) {
this(wildcard, null);
}
/**
* Construct a new wildcard filter for a single wildcard specifying case-sensitivity.
*
* @param wildcard the wildcard to match, not null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the pattern is null
*/
public WildcardFileFilter(String wildcard, IOCase caseSensitivity) {
if (wildcard == null) {
throw new IllegalArgumentException("The wildcard must not be null");
}
this.wildcards = new String[] { wildcard };
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
/**
* Construct a new case-sensitive wildcard filter for an array of wildcards.
* <p>
* The array is not cloned, so could be changed after constructing the
* instance. This would be inadvisable however.
*
* @param wildcards the array of wildcards to match
* @throws IllegalArgumentException if the pattern array is null
*/
public WildcardFileFilter(String[] wildcards) {
this(wildcards, null);
}
/**
* Construct a new wildcard filter for an array of wildcards specifying case-sensitivity.
* <p>
* The array is not cloned, so could be changed after constructing the
* instance. This would be inadvisable however.
*
* @param wildcards the array of wildcards to match, not null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the pattern array is null
*/
public WildcardFileFilter(String[] wildcards, IOCase caseSensitivity) {
if (wildcards == null) {
throw new IllegalArgumentException("The wildcard array must not be null");
}
this.wildcards = wildcards;
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
/**
* Construct a new case-sensitive wildcard filter for a list of wildcards.
*
* @param wildcards the list of wildcards to match, not null
* @throws IllegalArgumentException if the pattern list is null
* @throws ClassCastException if the list does not contain Strings
*/
public WildcardFileFilter(List wildcards) {
this(wildcards, null);
}
/**
* Construct a new wildcard filter for a list of wildcards specifying case-sensitivity.
*
* @param wildcards the list of wildcards to match, not null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the pattern list is null
* @throws ClassCastException if the list does not contain Strings
*/
public WildcardFileFilter(List wildcards, IOCase caseSensitivity) {
if (wildcards == null) {
throw new IllegalArgumentException("The wildcard list must not be null");
}
this.wildcards = (String[]) wildcards.toArray(new String[wildcards.size()]);
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
//-----------------------------------------------------------------------
/**
* Checks to see if the filename matches one of the wildcards.
*
* @param dir the file directory
* @param name the filename
* @return true if the filename matches one of the wildcards
*/
public boolean accept(File dir, String name) {
for (int i = 0; i < wildcards.length; i++) {
if (FilenameUtils.wildcardMatch(name, wildcards[i], caseSensitivity)) {
return true;
}
}
return false;
}
/**
* Checks to see if the filename matches one of the wildcards.
*
* @param file the file to check
* @return true if the filename matches one of the wildcards
*/
public boolean accept(File file) {
String name = file.getName();
for (int i = 0; i < wildcards.length; i++) {
if (FilenameUtils.wildcardMatch(name, wildcards[i], caseSensitivity)) {
return true;
}
}
return false;
}
/**
* Provide a String representaion of this file filter.
*
* @return a String representaion
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(super.toString());
buffer.append("(");
if (wildcards != null) {
for (int i = 0; i < wildcards.length; i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(wildcards[i]);
}
}
buffer.append(")");
return buffer.toString();
}
}

View File

@ -1,140 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
/**
* Filters files using the supplied wildcards.
* <p>
* This filter selects files, but not directories, based on one or more wildcards
* and using case-sensitive comparison.
* <p>
* The wildcard matcher uses the characters '?' and '*' to represent a
* single or multiple wildcard characters.
* This is the same as often found on Dos/Unix command lines.
* The extension check is case-sensitive.
* See {@link FilenameUtils#wildcardMatch} for more information.
* <p>
* For example:
* <pre>
* File dir = new File(".");
* FileFilter fileFilter = new WildcardFilter("*test*.java~*~");
* File[] files = dir.listFiles(fileFilter);
* for (int i = 0; i < files.length; i++) {
* System.out.println(files[i]);
* }
* </pre>
*
* @author Jason Anderson
* @version $Revision: 606381 $ $Date: 2007-12-22 02:03:16 +0000 (Sat, 22 Dec 2007) $
* @since Commons IO 1.1
* @deprecated Use WilcardFileFilter. Deprecated as this class performs directory
* filtering which it shouldn't do, but that can't be removed due to compatability.
*/
public class WildcardFilter extends AbstractFileFilter implements Serializable {
/** The wildcards that will be used to match filenames. */
private final String[] wildcards;
/**
* Construct a new case-sensitive wildcard filter for a single wildcard.
*
* @param wildcard the wildcard to match
* @throws IllegalArgumentException if the pattern is null
*/
public WildcardFilter(String wildcard) {
if (wildcard == null) {
throw new IllegalArgumentException("The wildcard must not be null");
}
this.wildcards = new String[] { wildcard };
}
/**
* Construct a new case-sensitive wildcard filter for an array of wildcards.
*
* @param wildcards the array of wildcards to match
* @throws IllegalArgumentException if the pattern array is null
*/
public WildcardFilter(String[] wildcards) {
if (wildcards == null) {
throw new IllegalArgumentException("The wildcard array must not be null");
}
this.wildcards = wildcards;
}
/**
* Construct a new case-sensitive wildcard filter for a list of wildcards.
*
* @param wildcards the list of wildcards to match
* @throws IllegalArgumentException if the pattern list is null
* @throws ClassCastException if the list does not contain Strings
*/
public WildcardFilter(List wildcards) {
if (wildcards == null) {
throw new IllegalArgumentException("The wildcard list must not be null");
}
this.wildcards = (String[]) wildcards.toArray(new String[wildcards.size()]);
}
//-----------------------------------------------------------------------
/**
* Checks to see if the filename matches one of the wildcards.
*
* @param dir the file directory
* @param name the filename
* @return true if the filename matches one of the wildcards
*/
public boolean accept(File dir, String name) {
if (dir != null && new File(dir, name).isDirectory()) {
return false;
}
for (int i = 0; i < wildcards.length; i++) {
if (FilenameUtils.wildcardMatch(name, wildcards[i])) {
return true;
}
}
return false;
}
/**
* Checks to see if the filename matches one of the wildcards.
*
* @param file the file to check
* @return true if the filename matches one of the wildcards
*/
public boolean accept(File file) {
if (file.isDirectory()) {
return false;
}
for (int i = 0; i < wildcards.length; i++) {
if (FilenameUtils.wildcardMatch(file.getName(), wildcards[i])) {
return true;
}
}
return false;
}
}

View File

@ -1,143 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--
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 compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html>
<body>
<p>This package defines an interface (IOFileFilter) that combines both
{@link java.io.FileFilter} and {@link java.io.FilenameFilter}. Besides
that the package offers a series of ready-to-use implementations of the
IOFileFilter interface including implementation that allow you to combine
other such filters.</p>
<p>These filter can be used to list files or in {@link java.awt.FileDialog},
for example.</p>
<p>There are a number of 'primitive' filters:</p>
<table>
<tbody>
<tr>
<td><a href="DirectoryFileFilter.html">DirectoryFilter</a></td>
<td>Only accept directories</td>
</tr>
<tr>
<td><a href="PrefixFileFilter.html">PrefixFileFilter</a></td>
<td>Filter based on a prefix</td>
</tr>
<tr>
<td><a href="SuffixFileFilter.html">SuffixFileFilter</a></td>
<td>Filter based on a suffix</td>
</tr>
<tr>
<td><a href="NameFileFilter.html">NameFileFilter</a></td>
<td>Filter based on a filename</td>
</tr>
<tr>
<td><a href="WildcardFileFilter.html">WildcardFileFilter</a></td>
<td>Filter based on wildcards</td>
</tr>
<tr>
<td><a href="AgeFileFilter.html">AgeFileFilter</a></td>
<td>Filter based on last modified time of file</td>
</tr>
<tr>
<td><a href="SizeFileFilter.html">SizeFileFilter</a></td>
<td>Filter based on file size</td>
</tr>
</tbody>
</table>
<p>And there are five 'boolean' filters:</p>
<table>
<tbody>
<tr>
<td><a href="TrueFileFilter.html">TrueFileFilter</a></td>
<td>Accept all files</td>
</tr>
<tr>
<td><a href="FalseFileFilter.html">FalseFileFilter</a></td>
<td>Accept no files</td>
</tr>
<tr>
<td><a href="NotFileFilter.html">NotFileFilter</a></td>
<td>Applies a logical NOT to an existing filter</td>
</tr>
<tr>
<td><a href="AndFileFilter.html">AndFileFilter</a></td>
<td>Combines two filters using a logical AND</td>
</tr>
<tr>
<td><a href="OrFileFilter.html">OrFileFilter</a></td>
<td>Combines two filter using a logical OR</td>
</tr>
</tbody>
</table>
<p>These boolean FilenameFilters can be nested, to allow arbitrary expressions.
For example, here is how one could print all non-directory files in the
current directory, starting with "A", and ending in ".java" or ".class":</p>
<pre>
File dir = new File(".");
String[] files = dir.list(
new AndFileFilter(
new AndFileFilter(
new PrefixFileFilter("A"),
new OrFileFilter(
new SuffixFileFilter(".class"),
new SuffixFileFilter(".java")
)
),
new NotFileFilter(
new DirectoryFileFilter()
)
)
);
for ( int i=0; i&lt;files.length; i++ ) {
System.out.println(files[i]);
}
</pre>
<p>This package also contains a utility class:
<a href="FileFilterUtils.html">FileFilterUtils</a>. It allows you to use all
file filters without having to put them in the import section. Here's how the
above example will look using FileFilterUtils:</p>
<pre>
File dir = new File(".");
String[] files = dir.list(
FileFilterUtils.andFileFilter(
FileFilterUtils.andFileFilter(
FileFilterUtils.prefixFileFilter("A"),
FileFilterUtils.orFileFilter(
FileFilterUtils.suffixFileFilter(".class"),
FileFilterUtils.suffixFileFilter(".java")
)
),
FileFilterUtils.notFileFilter(
FileFilterUtils.directoryFileFilter()
)
)
);
for ( int i=0; i&lt;files.length; i++ ) {
System.out.println(files[i]);
}
</pre>
<p>There are a few other goodies in that class so please have a look at the
documentation in detail.</p>
</body>
</html>

View File

@ -1,129 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.input;
import java.io.IOException;
import java.io.InputStream;
/**
* Proxy stream that closes and discards the underlying stream as soon as the
* end of input has been reached or when the stream is explicitly closed.
* Not even a reference to the underlying stream is kept after it has been
* closed, so any allocated in-memory buffers can be freed even if the
* client application still keeps a reference to the proxy stream.
* <p>
* This class is typically used to release any resources related to an open
* stream as soon as possible even if the client application (by not explicitly
* closing the stream when no longer needed) or the underlying stream (by not
* releasing resources once the last byte has been read) do not do that.
*
* @version $Id: AutoCloseInputStream.java 610010 2008-01-08 14:50:59Z niallp $
* @since Commons IO 1.4
*/
public class AutoCloseInputStream extends ProxyInputStream {
/**
* Creates an automatically closing proxy for the given input stream.
*
* @param in underlying input stream
*/
public AutoCloseInputStream(InputStream in) {
super(in);
}
/**
* Closes the underlying input stream and replaces the reference to it
* with a {@link ClosedInputStream} instance.
* <p>
* This method is automatically called by the read methods when the end
* of input has been reached.
* <p>
* Note that it is safe to call this method any number of times. The original
* underlying input stream is closed and discarded only once when this
* method is first called.
*
* @throws IOException if the underlying input stream can not be closed
*/
public void close() throws IOException {
in.close();
in = new ClosedInputStream();
}
/**
* Reads and returns a single byte from the underlying input stream.
* If the underlying stream returns -1, the {@link #close()} method is
* called to automatically close and discard the stream.
*
* @return next byte in the stream, or -1 if no more bytes are available
* @throws IOException if the stream could not be read or closed
*/
public int read() throws IOException {
int n = in.read();
if (n == -1) {
close();
}
return n;
}
/**
* Reads and returns bytes from the underlying input stream to the given
* buffer. If the underlying stream returns -1, the {@link #close()} method
* i called to automatically close and discard the stream.
*
* @param b buffer to which bytes from the stream are written
* @return number of bytes read, or -1 if no more bytes are available
* @throws IOException if the stream could not be read or closed
*/
public int read(byte[] b) throws IOException {
int n = in.read(b);
if (n == -1) {
close();
}
return n;
}
/**
* Reads and returns bytes from the underlying input stream to the given
* buffer. If the underlying stream returns -1, the {@link #close()} method
* i called to automatically close and discard the stream.
*
* @param b buffer to which bytes from the stream are written
* @param off start offset within the buffer
* @param len maximum number of bytes to read
* @return number of bytes read, or -1 if no more bytes are available
* @throws IOException if the stream could not be read or closed
*/
public int read(byte[] b, int off, int len) throws IOException {
int n = in.read(b, off, len);
if (n == -1) {
close();
}
return n;
}
/**
* Ensures that the stream is closed before it gets garbage-collected.
* As mentioned in {@link #close()}, this is a no-op if the stream has
* already been closed.
* @throws Throwable if an error occurs
*/
protected void finalize() throws Throwable {
close();
super.finalize();
}
}

View File

@ -1,155 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.input;
import java.io.Reader;
import java.io.Serializable;
/**
* {@link Reader} implementation that can read from String, StringBuffer,
* StringBuilder or CharBuffer.
* <p>
* <strong>Note:</strong> Supports {@link #mark(int)} and {@link #reset()}.
*
* @version $Revision: 610516 $ $Date: 2008-01-09 19:05:05 +0000 (Wed, 09 Jan 2008) $
* @since Commons IO 1.4
*/
public class CharSequenceReader extends Reader implements Serializable {
private final CharSequence charSequence;
private int idx;
private int mark;
/**
* Construct a new instance with the specified character sequence.
*
* @param charSequence The character sequence, may be <code>null</code>
*/
public CharSequenceReader(CharSequence charSequence) {
this.charSequence = (charSequence != null ? charSequence : "");
}
/**
* Close resets the file back to the start and removes any marked position.
*/
public void close() {
idx = 0;
mark = 0;
}
/**
* Mark the current position.
*
* @param readAheadLimit ignored
*/
public void mark(int readAheadLimit) {
mark = idx;
}
/**
* Mark is supported (returns true).
*
* @return <code>true</code>
*/
public boolean markSupported() {
return true;
}
/**
* Read a single character.
*
* @return the next character from the character sequence
* or -1 if the end has been reached.
*/
public int read() {
if (idx >= charSequence.length()) {
return -1;
} else {
return charSequence.charAt(idx++);
}
}
/**
* Read the sepcified number of characters into the array.
*
* @param array The array to store the characters in
* @param offset The starting position in the array to store
* @param length The maximum number of characters to read
* @return The number of characters read or -1 if there are
* no more
*/
public int read(char[] array, int offset, int length) {
if (idx >= charSequence.length()) {
return -1;
}
if (array == null) {
throw new NullPointerException("Character array is missing");
}
if (length < 0 || (offset + length) > array.length) {
throw new IndexOutOfBoundsException("Array Size=" + array.length +
", offset=" + offset + ", length=" + length);
}
int count = 0;
for (int i = 0; i < length; i++) {
int c = read();
if (c == -1) {
return count;
}
array[offset + i] = (char)c;
count++;
}
return count;
}
/**
* Reset the reader to the last marked position (or the beginning if
* mark has not been called).
*/
public void reset() {
idx = mark;
}
/**
* Skip the specified number of characters.
*
* @param n The number of characters to skip
* @return The actual number of characters skipped
*/
public long skip(long n) {
if (n < 0) {
throw new IllegalArgumentException(
"Number of characters to skip is less than zero: " + n);
}
if (idx >= charSequence.length()) {
return -1;
}
int dest = (int)Math.min(charSequence.length(), (idx + n));
int count = dest - idx;
idx = dest;
return count;
}
/**
* Return a String representation of the underlying
* character sequence.
*
* @return The contents of the character sequence
*/
public String toString() {
return charSequence.toString();
}
}

View File

@ -1,77 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.input;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.io.StreamCorruptedException;
/**
* A special ObjectInputStream that loads a class based on a specified
* <code>ClassLoader</code> rather than the system default.
* <p>
* This is useful in dynamic container environments.
*
* @author Paul Hammant
* @version $Id: ClassLoaderObjectInputStream.java 437567 2006-08-28 06:39:07Z bayard $
* @since Commons IO 1.1
*/
public class ClassLoaderObjectInputStream extends ObjectInputStream {
/** The class loader to use. */
private ClassLoader classLoader;
/**
* Constructs a new ClassLoaderObjectInputStream.
*
* @param classLoader the ClassLoader from which classes should be loaded
* @param inputStream the InputStream to work on
* @throws IOException in case of an I/O error
* @throws StreamCorruptedException if the stream is corrupted
*/
public ClassLoaderObjectInputStream(
ClassLoader classLoader, InputStream inputStream)
throws IOException, StreamCorruptedException {
super(inputStream);
this.classLoader = classLoader;
}
/**
* Resolve a class specified by the descriptor using the
* specified ClassLoader or the super ClassLoader.
*
* @param objectStreamClass descriptor of the class
* @return the Class object described by the ObjectStreamClass
* @throws IOException in case of an I/O error
* @throws ClassNotFoundException if the Class cannot be found
*/
protected Class resolveClass(ObjectStreamClass objectStreamClass)
throws IOException, ClassNotFoundException {
Class clazz = Class.forName(objectStreamClass.getName(), false, classLoader);
if (clazz != null) {
// the classloader knows of the class
return clazz;
} else {
// classloader knows not of class, let the super classloader do it
return super.resolveClass(objectStreamClass);
}
}
}

View File

@ -1,52 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.input;
import java.io.InputStream;
/**
* Proxy stream that prevents the underlying input stream from being closed.
* <p>
* This class is typically used in cases where an input stream needs to be
* passed to a component that wants to explicitly close the stream even if
* more input would still be available to other components.
*
* @version $Id: CloseShieldInputStream.java 587913 2007-10-24 15:47:30Z niallp $
* @since Commons IO 1.4
*/
public class CloseShieldInputStream extends ProxyInputStream {
/**
* Creates a proxy that shields the given input stream from being
* closed.
*
* @param in underlying input stream
*/
public CloseShieldInputStream(InputStream in) {
super(in);
}
/**
* Replaces the underlying input stream with a {@link ClosedInputStream}
* sentinel. The original input stream will remain open, but this proxy
* will appear closed.
*/
public void close() {
in = new ClosedInputStream();
}
}

View File

@ -1,48 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.input;
import java.io.InputStream;
/**
* Closed input stream. This stream returns -1 to all attempts to read
* something from the stream.
* <p>
* Typically uses of this class include testing for corner cases in methods
* that accept input streams and acting as a sentinel value instead of a
* <code>null</code> input stream.
*
* @version $Id: ClosedInputStream.java 601751 2007-12-06 14:55:45Z niallp $
* @since Commons IO 1.4
*/
public class ClosedInputStream extends InputStream {
/**
* A singleton.
*/
public static final ClosedInputStream CLOSED_INPUT_STREAM = new ClosedInputStream();
/**
* Returns -1 to indicate that the stream is closed.
*
* @return always -1
*/
public int read() {
return -1;
}
}

View File

@ -1,175 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.input;
import java.io.IOException;
import java.io.InputStream;
/**
* A decorating input stream that counts the number of bytes that have passed
* through the stream so far.
* <p>
* A typical use case would be during debugging, to ensure that data is being
* read as expected.
*
* @author Marcelo Liberato
* @version $Id: CountingInputStream.java 471628 2006-11-06 04:06:45Z bayard $
*/
public class CountingInputStream extends ProxyInputStream {
/** The count of bytes that have passed. */
private long count;
/**
* Constructs a new CountingInputStream.
*
* @param in the InputStream to delegate to
*/
public CountingInputStream(InputStream in) {
super(in);
}
//-----------------------------------------------------------------------
/**
* Reads a number of bytes into the byte array, keeping count of the
* number read.
*
* @param b the buffer into which the data is read, not null
* @return the total number of bytes read into the buffer, -1 if end of stream
* @throws IOException if an I/O error occurs
* @see java.io.InputStream#read(byte[])
*/
public int read(byte[] b) throws IOException {
int found = super.read(b);
this.count += (found >= 0) ? found : 0;
return found;
}
/**
* Reads a number of bytes into the byte array at a specific offset,
* keeping count of the number read.
*
* @param b the buffer into which the data is read, not null
* @param off the start offset in the buffer
* @param len the maximum number of bytes to read
* @return the total number of bytes read into the buffer, -1 if end of stream
* @throws IOException if an I/O error occurs
* @see java.io.InputStream#read(byte[], int, int)
*/
public int read(byte[] b, int off, int len) throws IOException {
int found = super.read(b, off, len);
this.count += (found >= 0) ? found : 0;
return found;
}
/**
* Reads the next byte of data adding to the count of bytes received
* if a byte is successfully read.
*
* @return the byte read, -1 if end of stream
* @throws IOException if an I/O error occurs
* @see java.io.InputStream#read()
*/
public int read() throws IOException {
int found = super.read();
this.count += (found >= 0) ? 1 : 0;
return found;
}
/**
* Skips the stream over the specified number of bytes, adding the skipped
* amount to the count.
*
* @param length the number of bytes to skip
* @return the actual number of bytes skipped
* @throws IOException if an I/O error occurs
* @see java.io.InputStream#skip(long)
*/
public long skip(final long length) throws IOException {
final long skip = super.skip(length);
this.count += skip;
return skip;
}
//-----------------------------------------------------------------------
/**
* The number of bytes that have passed through this stream.
* <p>
* NOTE: From v1.3 this method throws an ArithmeticException if the
* count is greater than can be expressed by an <code>int</code>.
* See {@link #getByteCount()} for a method using a <code>long</code>.
*
* @return the number of bytes accumulated
* @throws ArithmeticException if the byte count is too large
*/
public synchronized int getCount() {
long result = getByteCount();
if (result > Integer.MAX_VALUE) {
throw new ArithmeticException("The byte count " + result + " is too large to be converted to an int");
}
return (int) result;
}
/**
* Set the byte count back to 0.
* <p>
* NOTE: From v1.3 this method throws an ArithmeticException if the
* count is greater than can be expressed by an <code>int</code>.
* See {@link #resetByteCount()} for a method using a <code>long</code>.
*
* @return the count previous to resetting
* @throws ArithmeticException if the byte count is too large
*/
public synchronized int resetCount() {
long result = resetByteCount();
if (result > Integer.MAX_VALUE) {
throw new ArithmeticException("The byte count " + result + " is too large to be converted to an int");
}
return (int) result;
}
/**
* The number of bytes that have passed through this stream.
* <p>
* NOTE: This method is an alternative for <code>getCount()</code>
* and was added because that method returns an integer which will
* result in incorrect count for files over 2GB.
*
* @return the number of bytes accumulated
* @since Commons IO 1.3
*/
public synchronized long getByteCount() {
return this.count;
}
/**
* Set the byte count back to 0.
* <p>
* NOTE: This method is an alternative for <code>resetCount()</code>
* and was added because that method returns an integer which will
* result in incorrect count for files over 2GB.
*
* @return the count previous to resetting
* @since Commons IO 1.3
*/
public synchronized long resetByteCount() {
long tmp = this.count;
this.count = 0;
return tmp;
}
}

View File

@ -1,91 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.input;
import java.io.IOException;
import java.io.InputStream;
/**
* Data written to this stream is forwarded to a stream that has been associated
* with this thread.
*
* @author <a href="mailto:peter@apache.org">Peter Donald</a>
* @version $Revision: 437567 $ $Date: 2006-08-28 07:39:07 +0100 (Mon, 28 Aug 2006) $
*/
public class DemuxInputStream
extends InputStream
{
private InheritableThreadLocal m_streams = new InheritableThreadLocal();
/**
* Bind the specified stream to the current thread.
*
* @param input the stream to bind
* @return the InputStream that was previously active
*/
public InputStream bindStream( InputStream input )
{
InputStream oldValue = getStream();
m_streams.set( input );
return oldValue;
}
/**
* Closes stream associated with current thread.
*
* @throws IOException if an error occurs
*/
public void close()
throws IOException
{
InputStream input = getStream();
if( null != input )
{
input.close();
}
}
/**
* Read byte from stream associated with current thread.
*
* @return the byte read from stream
* @throws IOException if an error occurs
*/
public int read()
throws IOException
{
InputStream input = getStream();
if( null != input )
{
return input.read();
}
else
{
return -1;
}
}
/**
* Utility method to retrieve stream bound to current thread (if any).
*
* @return the input stream
*/
private InputStream getStream()
{
return (InputStream)m_streams.get();
}
}

View File

@ -1,329 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.input;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
/**
* A functional, light weight {@link InputStream} that emulates
* a stream of a specified size.
* <p>
* This implementation provides a light weight
* object for testing with an {@link InputStream}
* where the contents don't matter.
* <p>
* One use case would be for testing the handling of
* large {@link InputStream} as it can emulate that
* scenario without the overhead of actually processing
* large numbers of bytes - significantly speeding up
* test execution times.
* <p>
* This implementation returns zero from the method that
* reads a byte and leaves the array unchanged in the read
* methods that are passed a byte array.
* If alternative data is required the <code>processByte()</code> and
* <code>processBytes()</code> methods can be implemented to generate
* data, for example:
*
* <pre>
* public class TestInputStream extends NullInputStream {
* public TestInputStream(int size) {
* super(size);
* }
* protected int processByte() {
* return ... // return required value here
* }
* protected void processBytes(byte[] bytes, int offset, int length) {
* for (int i = offset; i < length; i++) {
* bytes[i] = ... // set array value here
* }
* }
* }
* </pre>
*
* @since Commons IO 1.3
* @version $Revision: 463529 $
*/
public class NullInputStream extends InputStream {
private long size;
private long position;
private long mark = -1;
private long readlimit;
private boolean eof;
private boolean throwEofException;
private boolean markSupported;
/**
* Create an {@link InputStream} that emulates a specified size
* which supports marking and does not throw EOFException.
*
* @param size The size of the input stream to emulate.
*/
public NullInputStream(long size) {
this(size, true, false);
}
/**
* Create an {@link InputStream} that emulates a specified
* size with option settings.
*
* @param size The size of the input stream to emulate.
* @param markSupported Whether this instance will support
* the <code>mark()</code> functionality.
* @param throwEofException Whether this implementation
* will throw an {@link EOFException} or return -1 when the
* end of file is reached.
*/
public NullInputStream(long size, boolean markSupported, boolean throwEofException) {
this.size = size;
this.markSupported = markSupported;
this.throwEofException = throwEofException;
}
/**
* Return the current position.
*
* @return the current position.
*/
public long getPosition() {
return position;
}
/**
* Return the size this {@link InputStream} emulates.
*
* @return The size of the input stream to emulate.
*/
public long getSize() {
return size;
}
/**
* Return the number of bytes that can be read.
*
* @return The number of bytes that can be read.
*/
public int available() {
long avail = size - position;
if (avail <= 0) {
return 0;
} else if (avail > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else {
return (int)avail;
}
}
/**
* Close this input stream - resets the internal state to
* the initial values.
*
* @throws IOException If an error occurs.
*/
public void close() throws IOException {
eof = false;
position = 0;
mark = -1;
}
/**
* Mark the current position.
*
* @param readlimit The number of bytes before this marked position
* is invalid.
* @throws UnsupportedOperationException if mark is not supported.
*/
public synchronized void mark(int readlimit) {
if (!markSupported) {
throw new UnsupportedOperationException("Mark not supported");
}
mark = position;
this.readlimit = readlimit;
}
/**
* Indicates whether <i>mark</i> is supported.
*
* @return Whether <i>mark</i> is supported or not.
*/
public boolean markSupported() {
return markSupported;
}
/**
* Read a byte.
*
* @return Either The byte value returned by <code>processByte()</code>
* or <code>-1</code> if the end of file has been reached and
* <code>throwEofException</code> is set to <code>false</code>.
* @throws EOFException if the end of file is reached and
* <code>throwEofException</code> is set to <code>true</code>.
* @throws IOException if trying to read past the end of file.
*/
public int read() throws IOException {
if (eof) {
throw new IOException("Read after end of file");
}
if (position == size) {
return doEndOfFile();
}
position++;
return processByte();
}
/**
* Read some bytes into the specified array.
*
* @param bytes The byte array to read into
* @return The number of bytes read or <code>-1</code>
* if the end of file has been reached and
* <code>throwEofException</code> is set to <code>false</code>.
* @throws EOFException if the end of file is reached and
* <code>throwEofException</code> is set to <code>true</code>.
* @throws IOException if trying to read past the end of file.
*/
public int read(byte[] bytes) throws IOException {
return read(bytes, 0, bytes.length);
}
/**
* Read the specified number bytes into an array.
*
* @param bytes The byte array to read into.
* @param offset The offset to start reading bytes into.
* @param length The number of bytes to read.
* @return The number of bytes read or <code>-1</code>
* if the end of file has been reached and
* <code>throwEofException</code> is set to <code>false</code>.
* @throws EOFException if the end of file is reached and
* <code>throwEofException</code> is set to <code>true</code>.
* @throws IOException if trying to read past the end of file.
*/
public int read(byte[] bytes, int offset, int length) throws IOException {
if (eof) {
throw new IOException("Read after end of file");
}
if (position == size) {
return doEndOfFile();
}
position += length;
int returnLength = length;
if (position > size) {
returnLength = length - (int)(position - size);
position = size;
}
processBytes(bytes, offset, returnLength);
return returnLength;
}
/**
* Reset the stream to the point when mark was last called.
*
* @throws UnsupportedOperationException if mark is not supported.
* @throws IOException If no position has been marked
* or the read limit has been exceed since the last position was
* marked.
*/
public synchronized void reset() throws IOException {
if (!markSupported) {
throw new UnsupportedOperationException("Mark not supported");
}
if (mark < 0) {
throw new IOException("No position has been marked");
}
if (position > (mark + readlimit)) {
throw new IOException("Marked position [" + mark +
"] is no longer valid - passed the read limit [" +
readlimit + "]");
}
position = mark;
eof = false;
}
/**
* Skip a specified number of bytes.
*
* @param numberOfBytes The number of bytes to skip.
* @return The number of bytes skipped or <code>-1</code>
* if the end of file has been reached and
* <code>throwEofException</code> is set to <code>false</code>.
* @throws EOFException if the end of file is reached and
* <code>throwEofException</code> is set to <code>true</code>.
* @throws IOException if trying to read past the end of file.
*/
public long skip(long numberOfBytes) throws IOException {
if (eof) {
throw new IOException("Skip after end of file");
}
if (position == size) {
return doEndOfFile();
}
position += numberOfBytes;
long returnLength = numberOfBytes;
if (position > size) {
returnLength = numberOfBytes - (position - size);
position = size;
}
return returnLength;
}
/**
* Return a byte value for the <code>read()</code> method.
* <p>
* This implementation returns zero.
*
* @return This implementation always returns zero.
*/
protected int processByte() {
// do nothing - overridable by subclass
return 0;
}
/**
* Process the bytes for the <code>read(byte[], offset, length)</code>
* method.
* <p>
* This implementation leaves the byte array unchanged.
*
* @param bytes The byte array
* @param offset The offset to start at.
* @param length The number of bytes.
*/
protected void processBytes(byte[] bytes, int offset, int length) {
// do nothing - overridable by subclass
}
/**
* Handle End of File.
*
* @return <code>-1</code> if <code>throwEofException</code> is
* set to <code>false</code>
* @throws EOFException if <code>throwEofException</code> is set
* to <code>true</code>.
*/
private int doEndOfFile() throws EOFException {
eof = true;
if (throwEofException) {
throw new EOFException();
}
return -1;
}
}

View File

@ -1,313 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.input;
import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;
/**
* A functional, light weight {@link Reader} that emulates
* a reader of a specified size.
* <p>
* This implementation provides a light weight
* object for testing with an {@link Reader}
* where the contents don't matter.
* <p>
* One use case would be for testing the handling of
* large {@link Reader} as it can emulate that
* scenario without the overhead of actually processing
* large numbers of characters - significantly speeding up
* test execution times.
* <p>
* This implementation returns a space from the method that
* reads a character and leaves the array unchanged in the read
* methods that are passed a character array.
* If alternative data is required the <code>processChar()</code> and
* <code>processChars()</code> methods can be implemented to generate
* data, for example:
*
* <pre>
* public class TestReader extends NullReader {
* public TestReader(int size) {
* super(size);
* }
* protected char processChar() {
* return ... // return required value here
* }
* protected void processChars(char[] chars, int offset, int length) {
* for (int i = offset; i < length; i++) {
* chars[i] = ... // set array value here
* }
* }
* }
* </pre>
*
* @since Commons IO 1.3
* @version $Revision: 463529 $
*/
public class NullReader extends Reader {
private long size;
private long position;
private long mark = -1;
private long readlimit;
private boolean eof;
private boolean throwEofException;
private boolean markSupported;
/**
* Create a {@link Reader} that emulates a specified size
* which supports marking and does not throw EOFException.
*
* @param size The size of the reader to emulate.
*/
public NullReader(long size) {
this(size, true, false);
}
/**
* Create a {@link Reader} that emulates a specified
* size with option settings.
*
* @param size The size of the reader to emulate.
* @param markSupported Whether this instance will support
* the <code>mark()</code> functionality.
* @param throwEofException Whether this implementation
* will throw an {@link EOFException} or return -1 when the
* end of file is reached.
*/
public NullReader(long size, boolean markSupported, boolean throwEofException) {
this.size = size;
this.markSupported = markSupported;
this.throwEofException = throwEofException;
}
/**
* Return the current position.
*
* @return the current position.
*/
public long getPosition() {
return position;
}
/**
* Return the size this {@link Reader} emulates.
*
* @return The size of the reader to emulate.
*/
public long getSize() {
return size;
}
/**
* Close this Reader - resets the internal state to
* the initial values.
*
* @throws IOException If an error occurs.
*/
public void close() throws IOException {
eof = false;
position = 0;
mark = -1;
}
/**
* Mark the current position.
*
* @param readlimit The number of characters before this marked position
* is invalid.
* @throws UnsupportedOperationException if mark is not supported.
*/
public synchronized void mark(int readlimit) {
if (!markSupported) {
throw new UnsupportedOperationException("Mark not supported");
}
mark = position;
this.readlimit = readlimit;
}
/**
* Indicates whether <i>mark</i> is supported.
*
* @return Whether <i>mark</i> is supported or not.
*/
public boolean markSupported() {
return markSupported;
}
/**
* Read a character.
*
* @return Either The character value returned by <code>processChar()</code>
* or <code>-1</code> if the end of file has been reached and
* <code>throwEofException</code> is set to <code>false</code>.
* @throws EOFException if the end of file is reached and
* <code>throwEofException</code> is set to <code>true</code>.
* @throws IOException if trying to read past the end of file.
*/
public int read() throws IOException {
if (eof) {
throw new IOException("Read after end of file");
}
if (position == size) {
return doEndOfFile();
}
position++;
return processChar();
}
/**
* Read some characters into the specified array.
*
* @param chars The character array to read into
* @return The number of characters read or <code>-1</code>
* if the end of file has been reached and
* <code>throwEofException</code> is set to <code>false</code>.
* @throws EOFException if the end of file is reached and
* <code>throwEofException</code> is set to <code>true</code>.
* @throws IOException if trying to read past the end of file.
*/
public int read(char[] chars) throws IOException {
return read(chars, 0, chars.length);
}
/**
* Read the specified number characters into an array.
*
* @param chars The character array to read into.
* @param offset The offset to start reading characters into.
* @param length The number of characters to read.
* @return The number of characters read or <code>-1</code>
* if the end of file has been reached and
* <code>throwEofException</code> is set to <code>false</code>.
* @throws EOFException if the end of file is reached and
* <code>throwEofException</code> is set to <code>true</code>.
* @throws IOException if trying to read past the end of file.
*/
public int read(char[] chars, int offset, int length) throws IOException {
if (eof) {
throw new IOException("Read after end of file");
}
if (position == size) {
return doEndOfFile();
}
position += length;
int returnLength = length;
if (position > size) {
returnLength = length - (int)(position - size);
position = size;
}
processChars(chars, offset, returnLength);
return returnLength;
}
/**
* Reset the stream to the point when mark was last called.
*
* @throws UnsupportedOperationException if mark is not supported.
* @throws IOException If no position has been marked
* or the read limit has been exceed since the last position was
* marked.
*/
public synchronized void reset() throws IOException {
if (!markSupported) {
throw new UnsupportedOperationException("Mark not supported");
}
if (mark < 0) {
throw new IOException("No position has been marked");
}
if (position > (mark + readlimit)) {
throw new IOException("Marked position [" + mark +
"] is no longer valid - passed the read limit [" +
readlimit + "]");
}
position = mark;
eof = false;
}
/**
* Skip a specified number of characters.
*
* @param numberOfChars The number of characters to skip.
* @return The number of characters skipped or <code>-1</code>
* if the end of file has been reached and
* <code>throwEofException</code> is set to <code>false</code>.
* @throws EOFException if the end of file is reached and
* <code>throwEofException</code> is set to <code>true</code>.
* @throws IOException if trying to read past the end of file.
*/
public long skip(long numberOfChars) throws IOException {
if (eof) {
throw new IOException("Skip after end of file");
}
if (position == size) {
return doEndOfFile();
}
position += numberOfChars;
long returnLength = numberOfChars;
if (position > size) {
returnLength = numberOfChars - (position - size);
position = size;
}
return returnLength;
}
/**
* Return a character value for the <code>read()</code> method.
* <p>
* This implementation returns zero.
*
* @return This implementation always returns zero.
*/
protected int processChar() {
// do nothing - overridable by subclass
return 0;
}
/**
* Process the characters for the <code>read(char[], offset, length)</code>
* method.
* <p>
* This implementation leaves the character array unchanged.
*
* @param chars The character array
* @param offset The offset to start at.
* @param length The number of characters.
*/
protected void processChars(char[] chars, int offset, int length) {
// do nothing - overridable by subclass
}
/**
* Handle End of File.
*
* @return <code>-1</code> if <code>throwEofException</code> is
* set to <code>false</code>
* @throws EOFException if <code>throwEofException</code> is set
* to <code>true</code>.
*/
private int doEndOfFile() throws EOFException {
eof = true;
if (throwEofException) {
throw new EOFException();
}
return -1;
}
}

View File

@ -1,129 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.input;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* A Proxy stream which acts as expected, that is it passes the method
* calls on to the proxied stream and doesn't change which methods are
* being called.
* <p>
* It is an alternative base class to FilterInputStream
* to increase reusability, because FilterInputStream changes the
* methods being called, such as read(byte[]) to read(byte[], int, int).
*
* @author Stephen Colebourne
* @version $Id: ProxyInputStream.java 610010 2008-01-08 14:50:59Z niallp $
*/
public abstract class ProxyInputStream extends FilterInputStream {
/**
* Constructs a new ProxyInputStream.
*
* @param proxy the InputStream to delegate to
*/
public ProxyInputStream(InputStream proxy) {
super(proxy);
// the proxy is stored in a protected superclass variable named 'in'
}
/**
* Invokes the delegate's <code>read()</code> method.
* @return the byte read or -1 if the end of stream
* @throws IOException if an I/O error occurs
*/
public int read() throws IOException {
return in.read();
}
/**
* Invokes the delegate's <code>read(byte[])</code> method.
* @param bts the buffer to read the bytes into
* @return the number of bytes read or -1 if the end of stream
* @throws IOException if an I/O error occurs
*/
public int read(byte[] bts) throws IOException {
return in.read(bts);
}
/**
* Invokes the delegate's <code>read(byte[], int, int)</code> method.
* @param bts the buffer to read the bytes into
* @param st The start offset
* @param end The number of bytes to read
* @return the number of bytes read or -1 if the end of stream
* @throws IOException if an I/O error occurs
*/
public int read(byte[] bts, int st, int end) throws IOException {
return in.read(bts, st, end);
}
/**
* Invokes the delegate's <code>skip(long)</code> method.
* @param ln the number of bytes to skip
* @return the number of bytes to skipped or -1 if the end of stream
* @throws IOException if an I/O error occurs
*/
public long skip(long ln) throws IOException {
return in.skip(ln);
}
/**
* Invokes the delegate's <code>available()</code> method.
* @return the number of available bytes
* @throws IOException if an I/O error occurs
*/
public int available() throws IOException {
return in.available();
}
/**
* Invokes the delegate's <code>close()</code> method.
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException {
in.close();
}
/**
* Invokes the delegate's <code>mark(int)</code> method.
* @param idx read ahead limit
*/
public synchronized void mark(int idx) {
in.mark(idx);
}
/**
* Invokes the delegate's <code>reset()</code> method.
* @throws IOException if an I/O error occurs
*/
public synchronized void reset() throws IOException {
in.reset();
}
/**
* Invokes the delegate's <code>markSupported()</code> method.
* @return true if mark is supported, otherwise false
*/
public boolean markSupported() {
return in.markSupported();
}
}

View File

@ -1,130 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.input;
import java.io.FilterReader;
import java.io.IOException;
import java.io.Reader;
/**
* A Proxy stream which acts as expected, that is it passes the method
* calls on to the proxied stream and doesn't change which methods are
* being called.
* <p>
* It is an alternative base class to FilterReader
* to increase reusability, because FilterReader changes the
* methods being called, such as read(char[]) to read(char[], int, int).
*
* @author Stephen Colebourne
* @version $Id: ProxyReader.java 610010 2008-01-08 14:50:59Z niallp $
*/
public abstract class ProxyReader extends FilterReader {
/**
* Constructs a new ProxyReader.
*
* @param proxy the Reader to delegate to
*/
public ProxyReader(Reader proxy) {
super(proxy);
// the proxy is stored in a protected superclass variable named 'in'
}
/**
* Invokes the delegate's <code>read()</code> method.
* @return the character read or -1 if the end of stream
* @throws IOException if an I/O error occurs
*/
public int read() throws IOException {
return in.read();
}
/**
* Invokes the delegate's <code>read(char[])</code> method.
* @param chr the buffer to read the characters into
* @return the number of characters read or -1 if the end of stream
* @throws IOException if an I/O error occurs
*/
public int read(char[] chr) throws IOException {
return in.read(chr);
}
/**
* Invokes the delegate's <code>read(char[], int, int)</code> method.
* @param chr the buffer to read the characters into
* @param st The start offset
* @param end The number of bytes to read
* @return the number of characters read or -1 if the end of stream
* @throws IOException if an I/O error occurs
*/
public int read(char[] chr, int st, int end) throws IOException {
return in.read(chr, st, end);
}
/**
* Invokes the delegate's <code>skip(long)</code> method.
* @param ln the number of bytes to skip
* @return the number of bytes to skipped or -1 if the end of stream
* @throws IOException if an I/O error occurs
*/
public long skip(long ln) throws IOException {
return in.skip(ln);
}
/**
* Invokes the delegate's <code>ready()</code> method.
* @return true if the stream is ready to be read
* @throws IOException if an I/O error occurs
*/
public boolean ready() throws IOException {
return in.ready();
}
/**
* Invokes the delegate's <code>close()</code> method.
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException {
in.close();
}
/**
* Invokes the delegate's <code>mark(int)</code> method.
* @param idx read ahead limit
* @throws IOException if an I/O error occurs
*/
public synchronized void mark(int idx) throws IOException {
in.mark(idx);
}
/**
* Invokes the delegate's <code>reset()</code> method.
* @throws IOException if an I/O error occurs
*/
public synchronized void reset() throws IOException {
in.reset();
}
/**
* Invokes the delegate's <code>markSupported()</code> method.
* @return true if mark is supported, otherwise false
*/
public boolean markSupported() {
return in.markSupported();
}
}

View File

@ -1,251 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.input;
import java.io.DataInput;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.EndianUtils;
/**
* DataInput for systems relying on little endian data formats.
* When read, values will be changed from little endian to big
* endian formats for internal usage.
* <p>
* <b>Origin of code: </b>Avalon Excalibur (IO)
*
* @author <a href="mailto:peter@apache.org">Peter Donald</a>
* @version CVS $Revision: 610010 $ $Date: 2008-01-08 14:50:59 +0000 (Tue, 08 Jan 2008) $
*/
public class SwappedDataInputStream extends ProxyInputStream
implements DataInput
{
/**
* Constructs a SwappedDataInputStream.
*
* @param input InputStream to read from
*/
public SwappedDataInputStream( InputStream input )
{
super( input );
}
/**
* Return <code>{@link #readByte()} == 0</code>
* @return the true if the byte read is zero, otherwise false
* @throws IOException if an I/O error occurs
* @throws EOFException if an end of file is reached unexpectedly
*/
public boolean readBoolean()
throws IOException, EOFException
{
return ( 0 == readByte() );
}
/**
* Invokes the delegate's <code>read()</code> method.
* @return the byte read or -1 if the end of stream
* @throws IOException if an I/O error occurs
* @throws EOFException if an end of file is reached unexpectedly
*/
public byte readByte()
throws IOException, EOFException
{
return (byte)in.read();
}
/**
* Reads a character delegating to {@link #readShort()}.
* @return the byte read or -1 if the end of stream
* @throws IOException if an I/O error occurs
* @throws EOFException if an end of file is reached unexpectedly
*/
public char readChar()
throws IOException, EOFException
{
return (char)readShort();
}
/**
* Delegates to {@link EndianUtils#readSwappedDouble(InputStream)}.
* @return the read long
* @throws IOException if an I/O error occurs
* @throws EOFException if an end of file is reached unexpectedly
*/
public double readDouble()
throws IOException, EOFException
{
return EndianUtils.readSwappedDouble( in );
}
/**
* Delegates to {@link EndianUtils#readSwappedFloat(InputStream)}.
* @return the read long
* @throws IOException if an I/O error occurs
* @throws EOFException if an end of file is reached unexpectedly
*/
public float readFloat()
throws IOException, EOFException
{
return EndianUtils.readSwappedFloat( in );
}
/**
* Invokes the delegate's <code>read(byte[] data, int, int)</code> method.
*
* @param data the buffer to read the bytes into
* @throws EOFException if an end of file is reached unexpectedly
* @throws IOException if an I/O error occurs
*/
public void readFully( byte[] data )
throws IOException, EOFException
{
readFully( data, 0, data.length );
}
/**
* Invokes the delegate's <code>read(byte[] data, int, int)</code> method.
*
* @param data the buffer to read the bytes into
* @param offset The start offset
* @param length The number of bytes to read
* @throws EOFException if an end of file is reached unexpectedly
* @throws IOException if an I/O error occurs
*/
public void readFully( byte[] data, int offset, int length )
throws IOException, EOFException
{
int remaining = length;
while( remaining > 0 )
{
int location = offset + ( length - remaining );
int count = read( data, location, remaining );
if( -1 == count )
{
throw new EOFException();
}
remaining -= count;
}
}
/**
* Delegates to {@link EndianUtils#readSwappedInteger(InputStream)}.
* @return the read long
* @throws EOFException if an end of file is reached unexpectedly
* @throws IOException if an I/O error occurs
*/
public int readInt()
throws IOException, EOFException
{
return EndianUtils.readSwappedInteger( in );
}
/**
* Not currently supported - throws {@link UnsupportedOperationException}.
* @return the line read
* @throws EOFException if an end of file is reached unexpectedly
* @throws IOException if an I/O error occurs
*/
public String readLine()
throws IOException, EOFException
{
throw new UnsupportedOperationException(
"Operation not supported: readLine()" );
}
/**
* Delegates to {@link EndianUtils#readSwappedLong(InputStream)}.
* @return the read long
* @throws EOFException if an end of file is reached unexpectedly
* @throws IOException if an I/O error occurs
*/
public long readLong()
throws IOException, EOFException
{
return EndianUtils.readSwappedLong( in );
}
/**
* Delegates to {@link EndianUtils#readSwappedShort(InputStream)}.
* @return the read long
* @throws EOFException if an end of file is reached unexpectedly
* @throws IOException if an I/O error occurs
*/
public short readShort()
throws IOException, EOFException
{
return EndianUtils.readSwappedShort( in );
}
/**
* Invokes the delegate's <code>read()</code> method.
* @return the byte read or -1 if the end of stream
* @throws EOFException if an end of file is reached unexpectedly
* @throws IOException if an I/O error occurs
*/
public int readUnsignedByte()
throws IOException, EOFException
{
return in.read();
}
/**
* Delegates to {@link EndianUtils#readSwappedUnsignedShort(InputStream)}.
* @return the read long
* @throws EOFException if an end of file is reached unexpectedly
* @throws IOException if an I/O error occurs
*/
public int readUnsignedShort()
throws IOException, EOFException
{
return EndianUtils.readSwappedUnsignedShort( in );
}
/**
* Not currently supported - throws {@link UnsupportedOperationException}.
* @return UTF String read
* @throws EOFException if an end of file is reached unexpectedly
* @throws IOException if an I/O error occurs
*/
public String readUTF()
throws IOException, EOFException
{
throw new UnsupportedOperationException(
"Operation not supported: readUTF()" );
}
/**
* Invokes the delegate's <code>skip(int)</code> method.
* @param count the number of bytes to skip
* @return the number of bytes to skipped or -1 if the end of stream
* @throws EOFException if an end of file is reached unexpectedly
* @throws IOException if an I/O error occurs
*/
public int skipBytes( int count )
throws IOException, EOFException
{
return (int)in.skip( count );
}
}

View File

@ -1,147 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.input;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* InputStream proxy that transparently writes a copy of all bytes read
* from the proxied stream to a given OutputStream. Using {@link #skip(long)}
* or {@link #mark(int)}/{@link #reset()} on the stream will result on some
* bytes from the input stream being skipped or duplicated in the output
* stream.
* <p>
* The proxied input stream is closed when the {@link #close()} method is
* called on this proxy. It is configurable whether the associated output
* stream will also closed.
*
* @version $Id: TeeInputStream.java 587913 2007-10-24 15:47:30Z niallp $
* @since Commons IO 1.4
*/
public class TeeInputStream extends ProxyInputStream {
/**
* The output stream that will receive a copy of all bytes read from the
* proxied input stream.
*/
private final OutputStream branch;
/**
* Flag for closing also the associated output stream when this
* stream is closed.
*/
private final boolean closeBranch;
/**
* Creates a TeeInputStream that proxies the given {@link InputStream}
* and copies all read bytes to the given {@link OutputStream}. The given
* output stream will not be closed when this stream gets closed.
*
* @param input input stream to be proxied
* @param branch output stream that will receive a copy of all bytes read
*/
public TeeInputStream(InputStream input, OutputStream branch) {
this(input, branch, false);
}
/**
* Creates a TeeInputStream that proxies the given {@link InputStream}
* and copies all read bytes to the given {@link OutputStream}. The given
* output stream will be closed when this stream gets closed if the
* closeBranch parameter is <code>true</code>.
*
* @param input input stream to be proxied
* @param branch output stream that will receive a copy of all bytes read
* @param closeBranch flag for closing also the output stream when this
* stream is closed
*/
public TeeInputStream(
InputStream input, OutputStream branch, boolean closeBranch) {
super(input);
this.branch = branch;
this.closeBranch = closeBranch;
}
/**
* Closes the proxied input stream and, if so configured, the associated
* output stream. An exception thrown from one stream will not prevent
* closing of the other stream.
*
* @throws IOException if either of the streams could not be closed
*/
public void close() throws IOException {
try {
super.close();
} finally {
if (closeBranch) {
branch.close();
}
}
}
/**
* Reads a single byte from the proxied input stream and writes it to
* the associated output stream.
*
* @return next byte from the stream, or -1 if the stream has ended
* @throws IOException if the stream could not be read (or written)
*/
public int read() throws IOException {
int ch = super.read();
if (ch != -1) {
branch.write(ch);
}
return ch;
}
/**
* Reads bytes from the proxied input stream and writes the read bytes
* to the associated output stream.
*
* @param bts byte buffer
* @param st start offset within the buffer
* @param end maximum number of bytes to read
* @return number of bytes read, or -1 if the stream has ended
* @throws IOException if the stream could not be read (or written)
*/
public int read(byte[] bts, int st, int end) throws IOException {
int n = super.read(bts, st, end);
if (n != -1) {
branch.write(bts, st, n);
}
return n;
}
/**
* Reads bytes from the proxied input stream and writes the read bytes
* to the associated output stream.
*
* @param bts byte buffer
* @return number of bytes read, or -1 if the stream has ended
* @throws IOException if the stream could not be read (or written)
*/
public int read(byte[] bts) throws IOException {
int n = super.read(bts);
if (n != -1) {
branch.write(bts, 0, n);
}
return n;
}
}

View File

@ -1,25 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--
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 compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html>
<body>
<p>
This package provides implementations of input classes, such as
<code>InputStream</code> and <code>Reader</code>.
</p>
</body>
</html>

View File

@ -1,308 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
/**
* This class implements an output stream in which the data is
* written into a byte array. The buffer automatically grows as data
* is written to it.
* <p>
* The data can be retrieved using <code>toByteArray()</code> and
* <code>toString()</code>.
* <p>
* Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in
* this class can be called after the stream has been closed without
* generating an <tt>IOException</tt>.
* <p>
* This is an alternative implementation of the java.io.ByteArrayOutputStream
* class. The original implementation only allocates 32 bytes at the beginning.
* As this class is designed for heavy duty it starts at 1024 bytes. In contrast
* to the original it doesn't reallocate the whole memory block but allocates
* additional buffers. This way no buffers need to be garbage collected and
* the contents don't have to be copied to the new buffer. This class is
* designed to behave exactly like the original. The only exception is the
* deprecated toString(int) method that has been ignored.
*
* @author <a href="mailto:jeremias@apache.org">Jeremias Maerki</a>
* @author Holger Hoffstatte
* @version $Id: ByteArrayOutputStream.java 610010 2008-01-08 14:50:59Z niallp $
*/
public class ByteArrayOutputStream extends OutputStream {
/** A singleton empty byte array. */
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
/** The list of buffers, which grows and never reduces. */
private List buffers = new ArrayList();
/** The index of the current buffer. */
private int currentBufferIndex;
/** The total count of bytes in all the filled buffers. */
private int filledBufferSum;
/** The current buffer. */
private byte[] currentBuffer;
/** The total count of bytes written. */
private int count;
/**
* Creates a new byte array output stream. The buffer capacity is
* initially 1024 bytes, though its size increases if necessary.
*/
public ByteArrayOutputStream() {
this(1024);
}
/**
* Creates a new byte array output stream, with a buffer capacity of
* the specified size, in bytes.
*
* @param size the initial size
* @throws IllegalArgumentException if size is negative
*/
public ByteArrayOutputStream(int size) {
if (size < 0) {
throw new IllegalArgumentException(
"Negative initial size: " + size);
}
needNewBuffer(size);
}
/**
* Return the appropriate <code>byte[]</code> buffer
* specified by index.
*
* @param index the index of the buffer required
* @return the buffer
*/
private byte[] getBuffer(int index) {
return (byte[]) buffers.get(index);
}
/**
* Makes a new buffer available either by allocating
* a new one or re-cycling an existing one.
*
* @param newcount the size of the buffer if one is created
*/
private void needNewBuffer(int newcount) {
if (currentBufferIndex < buffers.size() - 1) {
//Recycling old buffer
filledBufferSum += currentBuffer.length;
currentBufferIndex++;
currentBuffer = getBuffer(currentBufferIndex);
} else {
//Creating new buffer
int newBufferSize;
if (currentBuffer == null) {
newBufferSize = newcount;
filledBufferSum = 0;
} else {
newBufferSize = Math.max(
currentBuffer.length << 1,
newcount - filledBufferSum);
filledBufferSum += currentBuffer.length;
}
currentBufferIndex++;
currentBuffer = new byte[newBufferSize];
buffers.add(currentBuffer);
}
}
/**
* Write the bytes to byte array.
* @param b the bytes to write
* @param off The start offset
* @param len The number of bytes to write
*/
public void write(byte[] b, int off, int len) {
if ((off < 0)
|| (off > b.length)
|| (len < 0)
|| ((off + len) > b.length)
|| ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
synchronized (this) {
int newcount = count + len;
int remaining = len;
int inBufferPos = count - filledBufferSum;
while (remaining > 0) {
int part = Math.min(remaining, currentBuffer.length - inBufferPos);
System.arraycopy(b, off + len - remaining, currentBuffer, inBufferPos, part);
remaining -= part;
if (remaining > 0) {
needNewBuffer(newcount);
inBufferPos = 0;
}
}
count = newcount;
}
}
/**
* Write a byte to byte array.
* @param b the byte to write
*/
public synchronized void write(int b) {
int inBufferPos = count - filledBufferSum;
if (inBufferPos == currentBuffer.length) {
needNewBuffer(count + 1);
inBufferPos = 0;
}
currentBuffer[inBufferPos] = (byte) b;
count++;
}
/**
* Writes the entire contents of the specified input stream to this
* byte stream. Bytes from the input stream are read directly into the
* internal buffers of this streams.
*
* @param in the input stream to read from
* @return total number of bytes read from the input stream
* (and written to this stream)
* @throws IOException if an I/O error occurs while reading the input stream
* @since Commons IO 1.4
*/
public synchronized int write(InputStream in) throws IOException {
int readCount = 0;
int inBufferPos = count - filledBufferSum;
int n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos);
while (n != -1) {
readCount += n;
inBufferPos += n;
count += n;
if (inBufferPos == currentBuffer.length) {
needNewBuffer(currentBuffer.length);
inBufferPos = 0;
}
n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos);
}
return readCount;
}
/**
* Return the current size of the byte array.
* @return the current size of the byte array
*/
public synchronized int size() {
return count;
}
/**
* Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in
* this class can be called after the stream has been closed without
* generating an <tt>IOException</tt>.
*
* @throws IOException never (this method should not declare this exception
* but it has to now due to backwards compatability)
*/
public void close() throws IOException {
//nop
}
/**
* @see java.io.ByteArrayOutputStream#reset()
*/
public synchronized void reset() {
count = 0;
filledBufferSum = 0;
currentBufferIndex = 0;
currentBuffer = getBuffer(currentBufferIndex);
}
/**
* Writes the entire contents of this byte stream to the
* specified output stream.
*
* @param out the output stream to write to
* @throws IOException if an I/O error occurs, such as if the stream is closed
* @see java.io.ByteArrayOutputStream#writeTo(OutputStream)
*/
public synchronized void writeTo(OutputStream out) throws IOException {
int remaining = count;
for (int i = 0; i < buffers.size(); i++) {
byte[] buf = getBuffer(i);
int c = Math.min(buf.length, remaining);
out.write(buf, 0, c);
remaining -= c;
if (remaining == 0) {
break;
}
}
}
/**
* Gets the curent contents of this byte stream as a byte array.
* The result is independent of this stream.
*
* @return the current contents of this output stream, as a byte array
* @see java.io.ByteArrayOutputStream#toByteArray()
*/
public synchronized byte[] toByteArray() {
int remaining = count;
if (remaining == 0) {
return EMPTY_BYTE_ARRAY;
}
byte newbuf[] = new byte[remaining];
int pos = 0;
for (int i = 0; i < buffers.size(); i++) {
byte[] buf = getBuffer(i);
int c = Math.min(buf.length, remaining);
System.arraycopy(buf, 0, newbuf, pos, c);
pos += c;
remaining -= c;
if (remaining == 0) {
break;
}
}
return newbuf;
}
/**
* Gets the curent contents of this byte stream as a string.
* @return the contents of the byte array as a String
* @see java.io.ByteArrayOutputStream#toString()
*/
public String toString() {
return new String(toByteArray());
}
/**
* Gets the curent contents of this byte stream as a string
* using the specified encoding.
*
* @param enc the name of the character encoding
* @return the string converted from the byte array
* @throws UnsupportedEncodingException if the encoding is not supported
* @see java.io.ByteArrayOutputStream#toString(String)
*/
public String toString(String enc) throws UnsupportedEncodingException {
return new String(toByteArray(), enc);
}
}

View File

@ -1,52 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import java.io.OutputStream;
/**
* Proxy stream that prevents the underlying output stream from being closed.
* <p>
* This class is typically used in cases where an output stream needs to be
* passed to a component that wants to explicitly close the stream even if
* other components would still use the stream for output.
*
* @version $Id: CloseShieldOutputStream.java 587913 2007-10-24 15:47:30Z niallp $
* @since Commons IO 1.4
*/
public class CloseShieldOutputStream extends ProxyOutputStream {
/**
* Creates a proxy that shields the given output stream from being
* closed.
*
* @param out underlying output stream
*/
public CloseShieldOutputStream(OutputStream out) {
super(out);
}
/**
* Replaces the underlying output stream with a {@link ClosedOutputStream}
* sentinel. The original output stream will remain open, but this proxy
* will appear closed.
*/
public void close() {
out = new ClosedOutputStream();
}
}

View File

@ -1,50 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
/**
* Closed output stream. This stream throws an exception on all attempts to
* write something to the stream.
* <p>
* Typically uses of this class include testing for corner cases in methods
* that accept an output stream and acting as a sentinel value instead of
* a <code>null</code> output stream.
*
* @version $Id: ClosedOutputStream.java 601751 2007-12-06 14:55:45Z niallp $
* @since Commons IO 1.4
*/
public class ClosedOutputStream extends OutputStream {
/**
* A singleton.
*/
public static final ClosedOutputStream CLOSED_OUTPUT_STREAM = new ClosedOutputStream();
/**
* Throws an {@link IOException} to indicate that the stream is closed.
*
* @param b ignored
* @throws IOException always thrown
*/
public void write(int b) throws IOException {
throw new IOException("write(" + b + ") failed: stream is closed");
}
}

View File

@ -1,154 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
/**
* A decorating output stream that counts the number of bytes that have passed
* through the stream so far.
* <p>
* A typical use case would be during debugging, to ensure that data is being
* written as expected.
*
* @version $Id: CountingOutputStream.java 471628 2006-11-06 04:06:45Z bayard $
*/
public class CountingOutputStream extends ProxyOutputStream {
/** The count of bytes that have passed. */
private long count;
/**
* Constructs a new CountingOutputStream.
*
* @param out the OutputStream to write to
*/
public CountingOutputStream( OutputStream out ) {
super(out);
}
//-----------------------------------------------------------------------
/**
* Writes the contents of the specified byte array to this output stream
* keeping count of the number of bytes written.
*
* @param b the bytes to write, not null
* @throws IOException if an I/O error occurs
* @see java.io.OutputStream#write(byte[])
*/
public void write(byte[] b) throws IOException {
count += b.length;
super.write(b);
}
/**
* Writes a portion of the specified byte array to this output stream
* keeping count of the number of bytes written.
*
* @param b the bytes to write, not null
* @param off the start offset in the buffer
* @param len the maximum number of bytes to write
* @throws IOException if an I/O error occurs
* @see java.io.OutputStream#write(byte[], int, int)
*/
public void write(byte[] b, int off, int len) throws IOException {
count += len;
super.write(b, off, len);
}
/**
* Writes a single byte to the output stream adding to the count of the
* number of bytes written.
*
* @param b the byte to write
* @throws IOException if an I/O error occurs
* @see java.io.OutputStream#write(int)
*/
public void write(int b) throws IOException {
count++;
super.write(b);
}
//-----------------------------------------------------------------------
/**
* The number of bytes that have passed through this stream.
* <p>
* NOTE: From v1.3 this method throws an ArithmeticException if the
* count is greater than can be expressed by an <code>int</code>.
* See {@link #getByteCount()} for a method using a <code>long</code>.
*
* @return the number of bytes accumulated
* @throws ArithmeticException if the byte count is too large
*/
public synchronized int getCount() {
long result = getByteCount();
if (result > Integer.MAX_VALUE) {
throw new ArithmeticException("The byte count " + result + " is too large to be converted to an int");
}
return (int) result;
}
/**
* Set the byte count back to 0.
* <p>
* NOTE: From v1.3 this method throws an ArithmeticException if the
* count is greater than can be expressed by an <code>int</code>.
* See {@link #resetByteCount()} for a method using a <code>long</code>.
*
* @return the count previous to resetting
* @throws ArithmeticException if the byte count is too large
*/
public synchronized int resetCount() {
long result = resetByteCount();
if (result > Integer.MAX_VALUE) {
throw new ArithmeticException("The byte count " + result + " is too large to be converted to an int");
}
return (int) result;
}
/**
* The number of bytes that have passed through this stream.
* <p>
* NOTE: This method is an alternative for <code>getCount()</code>.
* It was added because that method returns an integer which will
* result in incorrect count for files over 2GB.
*
* @return the number of bytes accumulated
* @since Commons IO 1.3
*/
public synchronized long getByteCount() {
return this.count;
}
/**
* Set the byte count back to 0.
* <p>
* NOTE: This method is an alternative for <code>resetCount()</code>.
* It was added because that method returns an integer which will
* result in incorrect count for files over 2GB.
*
* @return the count previous to resetting
* @since Commons IO 1.3
*/
public synchronized long resetByteCount() {
long tmp = this.count;
this.count = 0;
return tmp;
}
}

View File

@ -1,269 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.io.IOUtils;
/**
* An output stream which will retain data in memory until a specified
* threshold is reached, and only then commit it to disk. If the stream is
* closed before the threshold is reached, the data will not be written to
* disk at all.
* <p>
* This class originated in FileUpload processing. In this use case, you do
* not know in advance the size of the file being uploaded. If the file is small
* you want to store it in memory (for speed), but if the file is large you want
* to store it to file (to avoid memory issues).
*
* @author <a href="mailto:martinc@apache.org">Martin Cooper</a>
* @author gaxzerow
*
* @version $Id: DeferredFileOutputStream.java 606381 2007-12-22 02:03:16Z ggregory $
*/
public class DeferredFileOutputStream
extends ThresholdingOutputStream
{
// ----------------------------------------------------------- Data members
/**
* The output stream to which data will be written prior to the theshold
* being reached.
*/
private ByteArrayOutputStream memoryOutputStream;
/**
* The output stream to which data will be written at any given time. This
* will always be one of <code>memoryOutputStream</code> or
* <code>diskOutputStream</code>.
*/
private OutputStream currentOutputStream;
/**
* The file to which output will be directed if the threshold is exceeded.
*/
private File outputFile;
/**
* The temporary file prefix.
*/
private String prefix;
/**
* The temporary file suffix.
*/
private String suffix;
/**
* The directory to use for temporary files.
*/
private File directory;
/**
* True when close() has been called successfully.
*/
private boolean closed = false;
// ----------------------------------------------------------- Constructors
/**
* Constructs an instance of this class which will trigger an event at the
* specified threshold, and save data to a file beyond that point.
*
* @param threshold The number of bytes at which to trigger an event.
* @param outputFile The file to which data is saved beyond the threshold.
*/
public DeferredFileOutputStream(int threshold, File outputFile)
{
super(threshold);
this.outputFile = outputFile;
memoryOutputStream = new ByteArrayOutputStream();
currentOutputStream = memoryOutputStream;
}
/**
* Constructs an instance of this class which will trigger an event at the
* specified threshold, and save data to a temporary file beyond that point.
*
* @param threshold The number of bytes at which to trigger an event.
* @param prefix Prefix to use for the temporary file.
* @param suffix Suffix to use for the temporary file.
* @param directory Temporary file directory.
*
* @since Commons IO 1.4
*/
public DeferredFileOutputStream(int threshold, String prefix, String suffix, File directory)
{
this(threshold, (File)null);
if (prefix == null) {
throw new IllegalArgumentException("Temporary file prefix is missing");
}
this.prefix = prefix;
this.suffix = suffix;
this.directory = directory;
}
// --------------------------------------- ThresholdingOutputStream methods
/**
* Returns the current output stream. This may be memory based or disk
* based, depending on the current state with respect to the threshold.
*
* @return The underlying output stream.
*
* @exception IOException if an error occurs.
*/
protected OutputStream getStream() throws IOException
{
return currentOutputStream;
}
/**
* Switches the underlying output stream from a memory based stream to one
* that is backed by disk. This is the point at which we realise that too
* much data is being written to keep in memory, so we elect to switch to
* disk-based storage.
*
* @exception IOException if an error occurs.
*/
protected void thresholdReached() throws IOException
{
if (prefix != null) {
outputFile = File.createTempFile(prefix, suffix, directory);
}
FileOutputStream fos = new FileOutputStream(outputFile);
memoryOutputStream.writeTo(fos);
currentOutputStream = fos;
memoryOutputStream = null;
}
// --------------------------------------------------------- Public methods
/**
* Determines whether or not the data for this output stream has been
* retained in memory.
*
* @return <code>true</code> if the data is available in memory;
* <code>false</code> otherwise.
*/
public boolean isInMemory()
{
return (!isThresholdExceeded());
}
/**
* Returns the data for this output stream as an array of bytes, assuming
* that the data has been retained in memory. If the data was written to
* disk, this method returns <code>null</code>.
*
* @return The data for this output stream, or <code>null</code> if no such
* data is available.
*/
public byte[] getData()
{
if (memoryOutputStream != null)
{
return memoryOutputStream.toByteArray();
}
return null;
}
/**
* Returns either the output file specified in the constructor or
* the temporary file created or null.
* <p>
* If the constructor specifying the file is used then it returns that
* same output file, even when threashold has not been reached.
* <p>
* If constructor specifying a temporary file prefix/suffix is used
* then the temporary file created once the threashold is reached is returned
* If the threshold was not reached then <code>null</code> is returned.
*
* @return The file for this output stream, or <code>null</code> if no such
* file exists.
*/
public File getFile()
{
return outputFile;
}
/**
* Closes underlying output stream, and mark this as closed
*
* @exception IOException if an error occurs.
*/
public void close() throws IOException
{
super.close();
closed = true;
}
/**
* Writes the data from this output stream to the specified output stream,
* after it has been closed.
*
* @param out output stream to write to.
* @exception IOException if this stream is not yet closed or an error occurs.
*/
public void writeTo(OutputStream out) throws IOException
{
// we may only need to check if this is closed if we are working with a file
// but we should force the habit of closing wether we are working with
// a file or memory.
if (!closed)
{
throw new IOException("Stream not closed");
}
if(isInMemory())
{
memoryOutputStream.writeTo(out);
}
else
{
FileInputStream fis = new FileInputStream(outputFile);
try {
IOUtils.copy(fis, out);
} finally {
IOUtils.closeQuietly(fis);
}
}
}
}

View File

@ -1,102 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
/**
* Data written to this stream is forwarded to a stream that has been associated
* with this thread.
*
* @author <a href="mailto:peter@apache.org">Peter Donald</a>
* @version $Revision: 437567 $ $Date: 2006-08-28 07:39:07 +0100 (Mon, 28 Aug 2006) $
*/
public class DemuxOutputStream
extends OutputStream
{
private InheritableThreadLocal m_streams = new InheritableThreadLocal();
/**
* Bind the specified stream to the current thread.
*
* @param output the stream to bind
* @return the OutputStream that was previously active
*/
public OutputStream bindStream( OutputStream output )
{
OutputStream stream = getStream();
m_streams.set( output );
return stream;
}
/**
* Closes stream associated with current thread.
*
* @throws IOException if an error occurs
*/
public void close()
throws IOException
{
OutputStream output = getStream();
if( null != output )
{
output.close();
}
}
/**
* Flushes stream associated with current thread.
*
* @throws IOException if an error occurs
*/
public void flush()
throws IOException
{
OutputStream output = getStream();
if( null != output )
{
output.flush();
}
}
/**
* Writes byte to stream associated with current thread.
*
* @param ch the byte to write to stream
* @throws IOException if an error occurs
*/
public void write( int ch )
throws IOException
{
OutputStream output = getStream();
if( null != output )
{
output.write( ch );
}
}
/**
* Utility method to retrieve stream bound to current thread (if any).
*
* @return the output stream
*/
private OutputStream getStream()
{
return (OutputStream)m_streams.get();
}
}

View File

@ -1,324 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
/**
* Writer of files that allows the encoding to be set.
* <p>
* This class provides a simple alternative to <code>FileWriter</code>
* that allows an encoding to be set. Unfortunately, it cannot subclass
* <code>FileWriter</code>.
* <p>
* By default, the file will be overwritten, but this may be changed to append.
* <p>
* The encoding must be specified using either the name of the {@link Charset},
* the {@link Charset}, or a {@link CharsetEncoder}. If the default encoding
* is required then use the {@link java.io.FileWriter} directly, rather than
* this implementation.
* <p>
*
*
* @since Commons IO 1.4
* @version $Id: FileWriterWithEncoding.java 611634 2008-01-13 20:35:00Z niallp $
*/
public class FileWriterWithEncoding extends Writer {
// Cannot extend ProxyWriter, as requires writer to be
// known when super() is called
/** The writer to decorate. */
private final Writer out;
/**
* Constructs a FileWriterWithEncoding with a file encoding.
*
* @param filename the name of the file to write to, not null
* @param encoding the encoding to use, not null
* @throws NullPointerException if the file name or encoding is null
* @throws IOException in case of an I/O error
*/
public FileWriterWithEncoding(String filename, String encoding) throws IOException {
this(new File(filename), encoding, false);
}
/**
* Constructs a FileWriterWithEncoding with a file encoding.
*
* @param filename the name of the file to write to, not null
* @param encoding the encoding to use, not null
* @param append true if content should be appended, false to overwrite
* @throws NullPointerException if the file name or encoding is null
* @throws IOException in case of an I/O error
*/
public FileWriterWithEncoding(String filename, String encoding, boolean append) throws IOException {
this(new File(filename), encoding, append);
}
/**
* Constructs a FileWriterWithEncoding with a file encoding.
*
* @param filename the name of the file to write to, not null
* @param encoding the encoding to use, not null
* @throws NullPointerException if the file name or encoding is null
* @throws IOException in case of an I/O error
*/
public FileWriterWithEncoding(String filename, Charset encoding) throws IOException {
this(new File(filename), encoding, false);
}
/**
* Constructs a FileWriterWithEncoding with a file encoding.
*
* @param filename the name of the file to write to, not null
* @param encoding the encoding to use, not null
* @param append true if content should be appended, false to overwrite
* @throws NullPointerException if the file name or encoding is null
* @throws IOException in case of an I/O error
*/
public FileWriterWithEncoding(String filename, Charset encoding, boolean append) throws IOException {
this(new File(filename), encoding, append);
}
/**
* Constructs a FileWriterWithEncoding with a file encoding.
*
* @param filename the name of the file to write to, not null
* @param encoding the encoding to use, not null
* @throws NullPointerException if the file name or encoding is null
* @throws IOException in case of an I/O error
*/
public FileWriterWithEncoding(String filename, CharsetEncoder encoding) throws IOException {
this(new File(filename), encoding, false);
}
/**
* Constructs a FileWriterWithEncoding with a file encoding.
*
* @param filename the name of the file to write to, not null
* @param encoding the encoding to use, not null
* @param append true if content should be appended, false to overwrite
* @throws NullPointerException if the file name or encoding is null
* @throws IOException in case of an I/O error
*/
public FileWriterWithEncoding(String filename, CharsetEncoder encoding, boolean append) throws IOException {
this(new File(filename), encoding, append);
}
/**
* Constructs a FileWriterWithEncoding with a file encoding.
*
* @param file the file to write to, not null
* @param encoding the encoding to use, not null
* @throws NullPointerException if the file or encoding is null
* @throws IOException in case of an I/O error
*/
public FileWriterWithEncoding(File file, String encoding) throws IOException {
this(file, encoding, false);
}
/**
* Constructs a FileWriterWithEncoding with a file encoding.
*
* @param file the file to write to, not null
* @param encoding the encoding to use, not null
* @param append true if content should be appended, false to overwrite
* @throws NullPointerException if the file or encoding is null
* @throws IOException in case of an I/O error
*/
public FileWriterWithEncoding(File file, String encoding, boolean append) throws IOException {
super();
this.out = initWriter(file, encoding, append);
}
/**
* Constructs a FileWriterWithEncoding with a file encoding.
*
* @param file the file to write to, not null
* @param encoding the encoding to use, not null
* @throws NullPointerException if the file or encoding is null
* @throws IOException in case of an I/O error
*/
public FileWriterWithEncoding(File file, Charset encoding) throws IOException {
this(file, encoding, false);
}
/**
* Constructs a FileWriterWithEncoding with a file encoding.
*
* @param file the file to write to, not null
* @param encoding the encoding to use, not null
* @param append true if content should be appended, false to overwrite
* @throws NullPointerException if the file or encoding is null
* @throws IOException in case of an I/O error
*/
public FileWriterWithEncoding(File file, Charset encoding, boolean append) throws IOException {
super();
this.out = initWriter(file, encoding, append);
}
/**
* Constructs a FileWriterWithEncoding with a file encoding.
*
* @param file the file to write to, not null
* @param encoding the encoding to use, not null
* @throws NullPointerException if the file or encoding is null
* @throws IOException in case of an I/O error
*/
public FileWriterWithEncoding(File file, CharsetEncoder encoding) throws IOException {
this(file, encoding, false);
}
/**
* Constructs a FileWriterWithEncoding with a file encoding.
*
* @param file the file to write to, not null
* @param encoding the encoding to use, not null
* @param append true if content should be appended, false to overwrite
* @throws NullPointerException if the file or encoding is null
* @throws IOException in case of an I/O error
*/
public FileWriterWithEncoding(File file, CharsetEncoder encoding, boolean append) throws IOException {
super();
this.out = initWriter(file, encoding, append);
}
//-----------------------------------------------------------------------
/**
* Initialise the wrapped file writer.
* Ensure that a cleanup occurs if the writer creation fails.
*
* @param file the file to be accessed
* @param encoding the encoding to use - may be Charset, CharsetEncoder or String
* @param append true to append
* @return the initialised writer
* @throws NullPointerException if the file or encoding is null
* @throws IOException if an error occurs
*/
private static Writer initWriter(File file, Object encoding, boolean append) throws IOException {
if (file == null) {
throw new NullPointerException("File is missing");
}
if (encoding == null) {
throw new NullPointerException("Encoding is missing");
}
boolean fileExistedAlready = file.exists();
OutputStream stream = null;
Writer writer = null;
try {
stream = new FileOutputStream(file, append);
if (encoding instanceof Charset) {
writer = new OutputStreamWriter(stream, (Charset)encoding);
} else if (encoding instanceof CharsetEncoder) {
writer = new OutputStreamWriter(stream, (CharsetEncoder)encoding);
} else {
writer = new OutputStreamWriter(stream, (String)encoding);
}
} catch (IOException ex) {
IOUtils.closeQuietly(writer);
IOUtils.closeQuietly(stream);
if (fileExistedAlready == false) {
FileUtils.deleteQuietly(file);
}
throw ex;
} catch (RuntimeException ex) {
IOUtils.closeQuietly(writer);
IOUtils.closeQuietly(stream);
if (fileExistedAlready == false) {
FileUtils.deleteQuietly(file);
}
throw ex;
}
return writer;
}
//-----------------------------------------------------------------------
/**
* Write a character.
* @param idx the character to write
* @throws IOException if an I/O error occurs
*/
public void write(int idx) throws IOException {
out.write(idx);
}
/**
* Write the characters from an array.
* @param chr the characters to write
* @throws IOException if an I/O error occurs
*/
public void write(char[] chr) throws IOException {
out.write(chr);
}
/**
* Write the specified characters from an array.
* @param chr the characters to write
* @param st The start offset
* @param end The number of characters to write
* @throws IOException if an I/O error occurs
*/
public void write(char[] chr, int st, int end) throws IOException {
out.write(chr, st, end);
}
/**
* Write the characters from a string.
* @param str the string to write
* @throws IOException if an I/O error occurs
*/
public void write(String str) throws IOException {
out.write(str);
}
/**
* Write the specified characters from a string.
* @param str the string to write
* @param st The start offset
* @param end The number of characters to write
* @throws IOException if an I/O error occurs
*/
public void write(String str, int st, int end) throws IOException {
out.write(str, st, end);
}
/**
* Flush the stream.
* @throws IOException if an I/O error occurs
*/
public void flush() throws IOException {
out.flush();
}
/**
* Close the stream.
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException {
out.close();
}
}

View File

@ -1,333 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
/**
* FileWriter that will create and honor lock files to allow simple
* cross thread file lock handling.
* <p>
* This class provides a simple alternative to <code>FileWriter</code>
* that will use a lock file to prevent duplicate writes.
* <p>
* By default, the file will be overwritten, but this may be changed to append.
* The lock directory may be specified, but defaults to the system property
* <code>java.io.tmpdir</code>.
* The encoding may also be specified, and defaults to the platform default.
*
* @author <a href="mailto:sanders@apache.org">Scott Sanders</a>
* @author <a href="mailto:ms@collab.net">Michael Salmon</a>
* @author <a href="mailto:jon@collab.net">Jon S. Stevens</a>
* @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
* @author Stephen Colebourne
* @author Andy Lehane
* @version $Id: LockableFileWriter.java 610010 2008-01-08 14:50:59Z niallp $
*/
public class LockableFileWriter extends Writer {
// Cannot extend ProxyWriter, as requires writer to be
// known when super() is called
/** The extension for the lock file. */
private static final String LCK = ".lck";
/** The writer to decorate. */
private final Writer out;
/** The lock file. */
private final File lockFile;
/**
* Constructs a LockableFileWriter.
* If the file exists, it is overwritten.
*
* @param fileName the file to write to, not null
* @throws NullPointerException if the file is null
* @throws IOException in case of an I/O error
*/
public LockableFileWriter(String fileName) throws IOException {
this(fileName, false, null);
}
/**
* Constructs a LockableFileWriter.
*
* @param fileName file to write to, not null
* @param append true if content should be appended, false to overwrite
* @throws NullPointerException if the file is null
* @throws IOException in case of an I/O error
*/
public LockableFileWriter(String fileName, boolean append) throws IOException {
this(fileName, append, null);
}
/**
* Constructs a LockableFileWriter.
*
* @param fileName the file to write to, not null
* @param append true if content should be appended, false to overwrite
* @param lockDir the directory in which the lock file should be held
* @throws NullPointerException if the file is null
* @throws IOException in case of an I/O error
*/
public LockableFileWriter(String fileName, boolean append, String lockDir) throws IOException {
this(new File(fileName), append, lockDir);
}
/**
* Constructs a LockableFileWriter.
* If the file exists, it is overwritten.
*
* @param file the file to write to, not null
* @throws NullPointerException if the file is null
* @throws IOException in case of an I/O error
*/
public LockableFileWriter(File file) throws IOException {
this(file, false, null);
}
/**
* Constructs a LockableFileWriter.
*
* @param file the file to write to, not null
* @param append true if content should be appended, false to overwrite
* @throws NullPointerException if the file is null
* @throws IOException in case of an I/O error
*/
public LockableFileWriter(File file, boolean append) throws IOException {
this(file, append, null);
}
/**
* Constructs a LockableFileWriter.
*
* @param file the file to write to, not null
* @param append true if content should be appended, false to overwrite
* @param lockDir the directory in which the lock file should be held
* @throws NullPointerException if the file is null
* @throws IOException in case of an I/O error
*/
public LockableFileWriter(File file, boolean append, String lockDir) throws IOException {
this(file, null, append, lockDir);
}
/**
* Constructs a LockableFileWriter with a file encoding.
*
* @param file the file to write to, not null
* @param encoding the encoding to use, null means platform default
* @throws NullPointerException if the file is null
* @throws IOException in case of an I/O error
*/
public LockableFileWriter(File file, String encoding) throws IOException {
this(file, encoding, false, null);
}
/**
* Constructs a LockableFileWriter with a file encoding.
*
* @param file the file to write to, not null
* @param encoding the encoding to use, null means platform default
* @param append true if content should be appended, false to overwrite
* @param lockDir the directory in which the lock file should be held
* @throws NullPointerException if the file is null
* @throws IOException in case of an I/O error
*/
public LockableFileWriter(File file, String encoding, boolean append,
String lockDir) throws IOException {
super();
// init file to create/append
file = file.getAbsoluteFile();
if (file.getParentFile() != null) {
FileUtils.forceMkdir(file.getParentFile());
}
if (file.isDirectory()) {
throw new IOException("File specified is a directory");
}
// init lock file
if (lockDir == null) {
lockDir = System.getProperty("java.io.tmpdir");
}
File lockDirFile = new File(lockDir);
FileUtils.forceMkdir(lockDirFile);
testLockDir(lockDirFile);
lockFile = new File(lockDirFile, file.getName() + LCK);
// check if locked
createLock();
// init wrapped writer
out = initWriter(file, encoding, append);
}
//-----------------------------------------------------------------------
/**
* Tests that we can write to the lock directory.
*
* @param lockDir the File representing the lock directory
* @throws IOException if we cannot write to the lock directory
* @throws IOException if we cannot find the lock file
*/
private void testLockDir(File lockDir) throws IOException {
if (!lockDir.exists()) {
throw new IOException(
"Could not find lockDir: " + lockDir.getAbsolutePath());
}
if (!lockDir.canWrite()) {
throw new IOException(
"Could not write to lockDir: " + lockDir.getAbsolutePath());
}
}
/**
* Creates the lock file.
*
* @throws IOException if we cannot create the file
*/
private void createLock() throws IOException {
synchronized (LockableFileWriter.class) {
if (!lockFile.createNewFile()) {
throw new IOException("Can't write file, lock " +
lockFile.getAbsolutePath() + " exists");
}
lockFile.deleteOnExit();
}
}
/**
* Initialise the wrapped file writer.
* Ensure that a cleanup occurs if the writer creation fails.
*
* @param file the file to be accessed
* @param encoding the encoding to use
* @param append true to append
* @return The initialised writer
* @throws IOException if an error occurs
*/
private Writer initWriter(File file, String encoding, boolean append) throws IOException {
boolean fileExistedAlready = file.exists();
OutputStream stream = null;
Writer writer = null;
try {
if (encoding == null) {
writer = new FileWriter(file.getAbsolutePath(), append);
} else {
stream = new FileOutputStream(file.getAbsolutePath(), append);
writer = new OutputStreamWriter(stream, encoding);
}
} catch (IOException ex) {
IOUtils.closeQuietly(writer);
IOUtils.closeQuietly(stream);
lockFile.delete();
if (fileExistedAlready == false) {
file.delete();
}
throw ex;
} catch (RuntimeException ex) {
IOUtils.closeQuietly(writer);
IOUtils.closeQuietly(stream);
lockFile.delete();
if (fileExistedAlready == false) {
file.delete();
}
throw ex;
}
return writer;
}
//-----------------------------------------------------------------------
/**
* Closes the file writer.
*
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException {
try {
out.close();
} finally {
lockFile.delete();
}
}
//-----------------------------------------------------------------------
/**
* Write a character.
* @param idx the character to write
* @throws IOException if an I/O error occurs
*/
public void write(int idx) throws IOException {
out.write(idx);
}
/**
* Write the characters from an array.
* @param chr the characters to write
* @throws IOException if an I/O error occurs
*/
public void write(char[] chr) throws IOException {
out.write(chr);
}
/**
* Write the specified characters from an array.
* @param chr the characters to write
* @param st The start offset
* @param end The number of characters to write
* @throws IOException if an I/O error occurs
*/
public void write(char[] chr, int st, int end) throws IOException {
out.write(chr, st, end);
}
/**
* Write the characters from a string.
* @param str the string to write
* @throws IOException if an I/O error occurs
*/
public void write(String str) throws IOException {
out.write(str);
}
/**
* Write the specified characters from a string.
* @param str the string to write
* @param st The start offset
* @param end The number of characters to write
* @throws IOException if an I/O error occurs
*/
public void write(String str, int st, int end) throws IOException {
out.write(str, st, end);
}
/**
* Flush the stream.
* @throws IOException if an I/O error occurs
*/
public void flush() throws IOException {
out.flush();
}
}

View File

@ -1,65 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
/**
* This OutputStream writes all data to the famous <b>/dev/null</b>.
* <p>
* This output stream has no destination (file/socket etc.) and all
* bytes written to it are ignored and lost.
*
* @author Jeremias Maerki
* @version $Id: NullOutputStream.java 610010 2008-01-08 14:50:59Z niallp $
*/
public class NullOutputStream extends OutputStream {
/**
* A singleton.
*/
public static final NullOutputStream NULL_OUTPUT_STREAM = new NullOutputStream();
/**
* Does nothing - output to <code>/dev/null</code>.
* @param b The bytes to write
* @param off The start offset
* @param len The number of bytes to write
*/
public void write(byte[] b, int off, int len) {
//to /dev/null
}
/**
* Does nothing - output to <code>/dev/null</code>.
* @param b The byte to write
*/
public void write(int b) {
//to /dev/null
}
/**
* Does nothing - output to <code>/dev/null</code>.
* @param b The bytes to write
* @throws IOException never
*/
public void write(byte[] b) throws IOException {
//to /dev/null
}
}

View File

@ -1,96 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import java.io.Writer;
/**
* This {@link Writer} writes all data to the famous <b>/dev/null</b>.
* <p>
* This <code>Writer</code> has no destination (file/socket etc.) and all
* characters written to it are ignored and lost.
*
* @version $Id: NullWriter.java 610010 2008-01-08 14:50:59Z niallp $
*/
public class NullWriter extends Writer {
/**
* A singleton.
*/
public static final NullWriter NULL_WRITER = new NullWriter();
/**
* Constructs a new NullWriter.
*/
public NullWriter() {
}
/**
* Does nothing - output to <code>/dev/null</code>.
* @param idx The character to write
*/
public void write(int idx) {
//to /dev/null
}
/**
* Does nothing - output to <code>/dev/null</code>.
* @param chr The characters to write
*/
public void write(char[] chr) {
//to /dev/null
}
/**
* Does nothing - output to <code>/dev/null</code>.
* @param chr The characters to write
* @param st The start offset
* @param end The number of characters to write
*/
public void write(char[] chr, int st, int end) {
//to /dev/null
}
/**
* Does nothing - output to <code>/dev/null</code>.
* @param str The string to write
*/
public void write(String str) {
//to /dev/null
}
/**
* Does nothing - output to <code>/dev/null</code>.
* @param str The string to write
* @param st The start offset
* @param end The number of characters to write
*/
public void write(String str, int st, int end) {
//to /dev/null
}
/** @see java.io.Writer#flush() */
public void flush() {
//to /dev/null
}
/** @see java.io.Writer#close() */
public void close() {
//to /dev/null
}
}

View File

@ -1,89 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* A Proxy stream which acts as expected, that is it passes the method
* calls on to the proxied stream and doesn't change which methods are
* being called. It is an alternative base class to FilterOutputStream
* to increase reusability.
*
* @author Stephen Colebourne
* @version $Id: ProxyOutputStream.java 610010 2008-01-08 14:50:59Z niallp $
*/
public class ProxyOutputStream extends FilterOutputStream {
/**
* Constructs a new ProxyOutputStream.
*
* @param proxy the OutputStream to delegate to
*/
public ProxyOutputStream(OutputStream proxy) {
super(proxy);
// the proxy is stored in a protected superclass variable named 'out'
}
/**
* Invokes the delegate's <code>write(int)</code> method.
* @param idx the byte to write
* @throws IOException if an I/O error occurs
*/
public void write(int idx) throws IOException {
out.write(idx);
}
/**
* Invokes the delegate's <code>write(byte[])</code> method.
* @param bts the bytes to write
* @throws IOException if an I/O error occurs
*/
public void write(byte[] bts) throws IOException {
out.write(bts);
}
/**
* Invokes the delegate's <code>write(byte[])</code> method.
* @param bts the bytes to write
* @param st The start offset
* @param end The number of bytes to write
* @throws IOException if an I/O error occurs
*/
public void write(byte[] bts, int st, int end) throws IOException {
out.write(bts, st, end);
}
/**
* Invokes the delegate's <code>flush()</code> method.
* @throws IOException if an I/O error occurs
*/
public void flush() throws IOException {
out.flush();
}
/**
* Invokes the delegate's <code>close()</code> method.
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException {
out.close();
}
}

View File

@ -1,111 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import java.io.FilterWriter;
import java.io.IOException;
import java.io.Writer;
/**
* A Proxy stream which acts as expected, that is it passes the method
* calls on to the proxied stream and doesn't change which methods are
* being called. It is an alternative base class to FilterWriter
* to increase reusability, because FilterWriter changes the
* methods being called, such as write(char[]) to write(char[], int, int)
* and write(String) to write(String, int, int).
*
* @author Stephen Colebourne
* @version $Id: ProxyWriter.java 610010 2008-01-08 14:50:59Z niallp $
*/
public class ProxyWriter extends FilterWriter {
/**
* Constructs a new ProxyWriter.
*
* @param proxy the Writer to delegate to
*/
public ProxyWriter(Writer proxy) {
super(proxy);
// the proxy is stored in a protected superclass variable named 'out'
}
/**
* Invokes the delegate's <code>write(int)</code> method.
* @param idx the character to write
* @throws IOException if an I/O error occurs
*/
public void write(int idx) throws IOException {
out.write(idx);
}
/**
* Invokes the delegate's <code>write(char[])</code> method.
* @param chr the characters to write
* @throws IOException if an I/O error occurs
*/
public void write(char[] chr) throws IOException {
out.write(chr);
}
/**
* Invokes the delegate's <code>write(char[], int, int)</code> method.
* @param chr the characters to write
* @param st The start offset
* @param end The number of characters to write
* @throws IOException if an I/O error occurs
*/
public void write(char[] chr, int st, int end) throws IOException {
out.write(chr, st, end);
}
/**
* Invokes the delegate's <code>write(String)</code> method.
* @param str the string to write
* @throws IOException if an I/O error occurs
*/
public void write(String str) throws IOException {
out.write(str);
}
/**
* Invokes the delegate's <code>write(String)</code> method.
* @param str the string to write
* @param st The start offset
* @param end The number of characters to write
* @throws IOException if an I/O error occurs
*/
public void write(String str, int st, int end) throws IOException {
out.write(str, st, end);
}
/**
* Invokes the delegate's <code>flush()</code> method.
* @throws IOException if an I/O error occurs
*/
public void flush() throws IOException {
out.flush();
}
/**
* Invokes the delegate's <code>close()</code> method.
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException {
out.close();
}
}

View File

@ -1,94 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
/**
* Classic splitter of OutputStream. Named after the unix 'tee'
* command. It allows a stream to be branched off so there
* are now two streams.
*
* @version $Id: TeeOutputStream.java 610010 2008-01-08 14:50:59Z niallp $
*/
public class TeeOutputStream extends ProxyOutputStream {
/** the second OutputStream to write to */
protected OutputStream branch;
/**
* Constructs a TeeOutputStream.
* @param out the main OutputStream
* @param branch the second OutputStream
*/
public TeeOutputStream( OutputStream out, OutputStream branch ) {
super(out);
this.branch = branch;
}
/**
* Write the bytes to both streams.
* @param b the bytes to write
* @throws IOException if an I/O error occurs
*/
public synchronized void write(byte[] b) throws IOException {
super.write(b);
this.branch.write(b);
}
/**
* Write the specified bytes to both streams.
* @param b the bytes to write
* @param off The start offset
* @param len The number of bytes to write
* @throws IOException if an I/O error occurs
*/
public synchronized void write(byte[] b, int off, int len) throws IOException {
super.write(b, off, len);
this.branch.write(b, off, len);
}
/**
* Write a byte to both streams.
* @param b the byte to write
* @throws IOException if an I/O error occurs
*/
public synchronized void write(int b) throws IOException {
super.write(b);
this.branch.write(b);
}
/**
* Flushes both streams.
* @throws IOException if an I/O error occurs
*/
public void flush() throws IOException {
super.flush();
this.branch.flush();
}
/**
* Closes both streams.
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException {
super.close();
this.branch.close();
}
}

View File

@ -1,257 +0,0 @@
/*
* 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 compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
/**
* An output stream which triggers an event when a specified number of bytes of
* data have been written to it. The event can be used, for example, to throw
* an exception if a maximum has been reached, or to switch the underlying
* stream type when the threshold is exceeded.
* <p>
* This class overrides all <code>OutputStream</code> methods. However, these
* overrides ultimately call the corresponding methods in the underlying output
* stream implementation.
* <p>
* NOTE: This implementation may trigger the event <em>before</em> the threshold
* is actually reached, since it triggers when a pending write operation would
* cause the threshold to be exceeded.
*
* @author <a href="mailto:martinc@apache.org">Martin Cooper</a>
*
* @version $Id: ThresholdingOutputStream.java 540714 2007-05-22 19:39:44Z niallp $
*/
public abstract class ThresholdingOutputStream
extends OutputStream
{
// ----------------------------------------------------------- Data members
/**
* The threshold at which the event will be triggered.
*/
private int threshold;
/**
* The number of bytes written to the output stream.
*/
private long written;
/**
* Whether or not the configured threshold has been exceeded.
*/
private boolean thresholdExceeded;
// ----------------------------------------------------------- Constructors
/**
* Constructs an instance of this class which will trigger an event at the
* specified threshold.
*
* @param threshold The number of bytes at which to trigger an event.
*/
public ThresholdingOutputStream(int threshold)
{
this.threshold = threshold;
}
// --------------------------------------------------- OutputStream methods
/**
* Writes the specified byte to this output stream.
*
* @param b The byte to be written.
*
* @exception IOException if an error occurs.
*/
public void write(int b) throws IOException
{
checkThreshold(1);
getStream().write(b);
written++;
}
/**
* Writes <code>b.length</code> bytes from the specified byte array to this
* output stream.
*
* @param b The array of bytes to be written.
*
* @exception IOException if an error occurs.
*/
public void write(byte b[]) throws IOException
{
checkThreshold(b.length);
getStream().write(b);
written += b.length;
}
/**
* Writes <code>len</code> bytes from the specified byte array starting at
* offset <code>off</code> to this output stream.
*
* @param b The byte array from which the data will be written.
* @param off The start offset in the byte array.
* @param len The number of bytes to write.
*
* @exception IOException if an error occurs.
*/
public void write(byte b[], int off, int len) throws IOException
{
checkThreshold(len);
getStream().write(b, off, len);
written += len;
}
/**
* Flushes this output stream and forces any buffered output bytes to be
* written out.
*
* @exception IOException if an error occurs.
*/
public void flush() throws IOException
{
getStream().flush();
}
/**
* Closes this output stream and releases any system resources associated
* with this stream.
*
* @exception IOException if an error occurs.
*/
public void close() throws IOException
{
try
{
flush();
}
catch (IOException ignored)
{
// ignore
}
getStream().close();
}
// --------------------------------------------------------- Public methods
/**
* Returns the threshold, in bytes, at which an event will be triggered.
*
* @return The threshold point, in bytes.
*/
public int getThreshold()
{
return threshold;
}
/**
* Returns the number of bytes that have been written to this output stream.
*
* @return The number of bytes written.
*/
public long getByteCount()
{
return written;
}
/**
* Determines whether or not the configured threshold has been exceeded for
* this output stream.
*
* @return <code>true</code> if the threshold has been reached;
* <code>false</code> otherwise.
*/
public boolean isThresholdExceeded()
{
return (written > threshold);
}
// ------------------------------------------------------ Protected methods
/**
* Checks to see if writing the specified number of bytes would cause the
* configured threshold to be exceeded. If so, triggers an event to allow
* a concrete implementation to take action on this.
*
* @param count The number of bytes about to be written to the underlying
* output stream.
*
* @exception IOException if an error occurs.
*/
protected void checkThreshold(int count) throws IOException
{
if (!thresholdExceeded && (written + count > threshold))
{
thresholdExceeded = true;
thresholdReached();
}
}
/**
* Resets the byteCount to zero. You can call this from
* {@link #thresholdReached()} if you want the event to be triggered again.
*/
protected void resetByteCount()
{
this.thresholdExceeded = false;
this.written = 0;
}
// ------------------------------------------------------- Abstract methods
/**
* Returns the underlying output stream, to which the corresponding
* <code>OutputStream</code> methods in this class will ultimately delegate.
*
* @return The underlying output stream.
*
* @exception IOException if an error occurs.
*/
protected abstract OutputStream getStream() throws IOException;
/**
* Indicates that the configured threshold has been reached, and that a
* subclass should take whatever action necessary on this event. This may
* include changing the underlying output stream.
*
* @exception IOException if an error occurs.
*/
protected abstract void thresholdReached() throws IOException;
}

View File

@ -1,25 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--
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 compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html>
<body>
<p>
This package provides implementations of output classes, such as
<code>OutputStream</code> and <code>Writer</code>.
</p>
</body>
</html>

View File

@ -1,32 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--
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 compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html>
<body bgcolor="white">
<p>
The commons-io component contains utility classes,
filters, streams, readers and writers.
</p>
<p>
These classes aim to add to the standard JDK IO classes.
The utilities provide convenience wrappers around the JDK, simplifying
various operations into pre-tested units of code.
The filters and streams provide useful implementations that perhaps should
be in the JDK itself.
</p>
</body>
</html>

View File

@ -1,47 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--
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 compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html>
<body bgcolor="white">
<p>
This package defines utility classes for working with streams, readers,
writers and files. The most commonly used classes are described here:
</p>
<p>
<b>IOUtils</b> is the most frequently used class.
It provides operations to read, write, copy and close streams.
</p>
<p>
<b>FileUtils</b> provides operations based around the JDK File class.
These include reading, writing, copying, comparing and deleting.
</p>
<p>
<b>FilenameUtils</b> provides utilities based on filenames.
This utility class manipulates filenames without using File objects.
It aims to simplify the transition between Windows and Unix.
Before using this class however, you should consider whether you should
be using File objects.
</p>
<p>
<b>FileSystemUtils</b> allows access to the filing system in ways the JDK
does not support. At present this allows you to get the free space on a drive.
</p>
<p>
<b>EndianUtils</b> swaps data between Big-Endian and Little-Endian formats.
</p>
</body>
</html>