first commit

This commit is contained in:
MaddoScientisto 2026-03-14 20:04:39 +01:00
commit 4d332ef662
27586 changed files with 3281783 additions and 0 deletions

View file

@ -0,0 +1,203 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -0,0 +1,13 @@
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.6.5
Created-By: 1.3.1_09-85 ("Apple Computer, Inc.")
Package: org.apache.commons.io
Extension-Name: commons-io
Specification-Version: 1.3.1
Specification-Vendor: Apache Software Foundation
Specification-Title: Commons IO
Implementation-Version: 1.3.1
Implementation-Vendor: Apache Software Foundation
Implementation-Title: Commons IO
Implementation-Vendor-Id: org.apache

View file

@ -0,0 +1,6 @@
Apache Jakarta Commons IO
Copyright 2001-2007 The Apache Software Foundation
This product includes software developed by
The Apache Software Foundation (http://www.apache.org/).

View file

@ -0,0 +1,78 @@
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;
public class CopyUtils {
private static final int DEFAULT_BUFFER_SIZE = 4096;
public static void copy(byte[] input, OutputStream output) throws IOException {
output.write(input);
}
public static void copy(byte[] input, Writer output) throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(input);
copy(in, output);
}
public static void copy(byte[] input, Writer output, String encoding) throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(input);
copy(in, output, encoding);
}
public static int copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[4096];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
public static int copy(Reader input, Writer output) throws IOException {
char[] buffer = new char[4096];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
public static void copy(InputStream input, Writer output) throws IOException {
InputStreamReader in = new InputStreamReader(input);
copy(in, output);
}
public static void copy(InputStream input, Writer output, String encoding) throws IOException {
InputStreamReader in = new InputStreamReader(input, encoding);
copy(in, output);
}
public static void copy(Reader input, OutputStream output) throws IOException {
OutputStreamWriter out = new OutputStreamWriter(output);
copy(input, out);
out.flush();
}
public static void copy(String input, OutputStream output) throws IOException {
StringReader in = new StringReader(input);
OutputStreamWriter out = new OutputStreamWriter(output);
copy(in, out);
out.flush();
}
public static void copy(String input, Writer output) throws IOException {
output.write(input);
}
}

View file

@ -0,0 +1,132 @@
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;
public abstract class DirectoryWalker {
private final FileFilter filter;
private final int depthLimit;
protected DirectoryWalker() {
this(null, -1);
}
protected DirectoryWalker(FileFilter filter, int depthLimit) {
this.filter = filter;
this.depthLimit = depthLimit;
}
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;
}
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);
}
}
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 (this.depthLimit < 0 || childDepth <= this.depthLimit) {
checkIfCancelled(directory, depth, results);
File[] childFiles = (this.filter == null) ? directory.listFiles() : directory.listFiles(this.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);
}
protected final void checkIfCancelled(File file, int depth, Collection results) throws IOException {
if (handleIsCancelled(file, depth, results))
throw new CancelException(file, depth);
}
protected boolean handleIsCancelled(File file, int depth, Collection results) throws IOException {
return false;
}
protected void handleCancelled(File startDirectory, Collection results, CancelException cancel) throws IOException {
throw cancel;
}
protected void handleStart(File startDirectory, Collection results) throws IOException {}
protected boolean handleDirectory(File directory, int depth, Collection results) throws IOException {
return true;
}
protected void handleDirectoryStart(File directory, int depth, Collection results) throws IOException {}
protected void handleFile(File file, int depth, Collection results) throws IOException {}
protected void handleRestricted(File directory, int depth, Collection results) throws IOException {}
protected void handleDirectoryEnd(File directory, int depth, Collection results) throws IOException {}
protected void handleEnd(Collection results) throws IOException {}
public static class CancelException extends IOException {
private static final long serialVersionUID = 1347339620135041008L;
private File file;
private int depth = -1;
public CancelException(File file, int depth) {
this("Operation Cancelled", file, depth);
}
public CancelException(String message, File file, int depth) {
super(message);
this.file = file;
this.depth = depth;
}
public File getFile() {
return this.file;
}
public int getDepth() {
return this.depth;
}
}
}

View file

@ -0,0 +1,168 @@
package org.apache.commons.io;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class EndianUtils {
public static short swapShort(short value) {
return (short)(((value >> 0 & 0xFF) << 8) + ((value >> 8 & 0xFF) << 0));
}
public static int swapInteger(int value) {
return ((value >> 0 & 0xFF) << 24) + ((value >> 8 & 0xFF) << 16) + ((value >> 16 & 0xFF) << 8) + ((value >> 24 & 0xFF) << 0);
}
public static long swapLong(long value) {
return ((value >> 0L & 0xFFL) << 56L) + ((value >> 8L & 0xFFL) << 48L) + ((value >> 16L & 0xFFL) << 40L) + ((value >> 24L & 0xFFL) << 32L) + ((value >> 32L & 0xFFL) << 24L) + ((value >> 40L & 0xFFL) << 16L) + ((value >> 48L & 0xFFL) << 8L) + ((value >> 56L & 0xFFL) << 0L);
}
public static float swapFloat(float value) {
return Float.intBitsToFloat(swapInteger(Float.floatToIntBits(value)));
}
public static double swapDouble(double value) {
return Double.longBitsToDouble(swapLong(Double.doubleToLongBits(value)));
}
public static void writeSwappedShort(byte[] data, int offset, short value) {
data[offset + 0] = (byte)(value >> 0 & 0xFF);
data[offset + 1] = (byte)(value >> 8 & 0xFF);
}
public static short readSwappedShort(byte[] data, int offset) {
return (short)(((data[offset + 0] & 0xFF) << 0) + ((data[offset + 1] & 0xFF) << 8));
}
public static int readSwappedUnsignedShort(byte[] data, int offset) {
return ((data[offset + 0] & 0xFF) << 0) + ((data[offset + 1] & 0xFF) << 8);
}
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);
}
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);
}
public static long readSwappedUnsignedInteger(byte[] data, int offset) {
return (long)(((data[offset + 0] & 0xFF) << 0) + ((data[offset + 1] & 0xFF) << 8) + ((data[offset + 2] & 0xFF) << 16) + ((data[offset + 3] & 0xFF) << 24));
}
public static void writeSwappedLong(byte[] data, int offset, long value) {
data[offset + 0] = (byte)(int)(value >> 0L & 0xFFL);
data[offset + 1] = (byte)(int)(value >> 8L & 0xFFL);
data[offset + 2] = (byte)(int)(value >> 16L & 0xFFL);
data[offset + 3] = (byte)(int)(value >> 24L & 0xFFL);
data[offset + 4] = (byte)(int)(value >> 32L & 0xFFL);
data[offset + 5] = (byte)(int)(value >> 40L & 0xFFL);
data[offset + 6] = (byte)(int)(value >> 48L & 0xFFL);
data[offset + 7] = (byte)(int)(value >> 56L & 0xFFL);
}
public static long readSwappedLong(byte[] data, int offset) {
long low = (long)(((data[offset + 0] & 0xFF) << 0) + ((data[offset + 1] & 0xFF) << 8) + ((data[offset + 2] & 0xFF) << 16) + ((data[offset + 3] & 0xFF) << 24));
long high = (long)(((data[offset + 4] & 0xFF) << 0) + ((data[offset + 5] & 0xFF) << 8) + ((data[offset + 6] & 0xFF) << 16) + ((data[offset + 7] & 0xFF) << 24));
return (high << 32L) + (0xFFFFFFFFL & low);
}
public static void writeSwappedFloat(byte[] data, int offset, float value) {
writeSwappedInteger(data, offset, Float.floatToIntBits(value));
}
public static float readSwappedFloat(byte[] data, int offset) {
return Float.intBitsToFloat(readSwappedInteger(data, offset));
}
public static void writeSwappedDouble(byte[] data, int offset, double value) {
writeSwappedLong(data, offset, Double.doubleToLongBits(value));
}
public static double readSwappedDouble(byte[] data, int offset) {
return Double.longBitsToDouble(readSwappedLong(data, offset));
}
public static void writeSwappedShort(OutputStream output, short value) throws IOException {
output.write((byte)(value >> 0 & 0xFF));
output.write((byte)(value >> 8 & 0xFF));
}
public static short readSwappedShort(InputStream input) throws IOException {
return (short)(((read(input) & 0xFF) << 0) + ((read(input) & 0xFF) << 8));
}
public static int readSwappedUnsignedShort(InputStream input) throws IOException {
int value1 = read(input);
int value2 = read(input);
return ((value1 & 0xFF) << 0) + ((value2 & 0xFF) << 8);
}
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));
}
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);
}
public static long readSwappedUnsignedInteger(InputStream input) throws IOException {
int value1 = read(input);
int value2 = read(input);
int value3 = read(input);
int value4 = read(input);
return (long)(((value1 & 0xFF) << 0) + ((value2 & 0xFF) << 8) + ((value3 & 0xFF) << 16) + ((value4 & 0xFF) << 24));
}
public static void writeSwappedLong(OutputStream output, long value) throws IOException {
output.write((byte)(int)(value >> 0L & 0xFFL));
output.write((byte)(int)(value >> 8L & 0xFFL));
output.write((byte)(int)(value >> 16L & 0xFFL));
output.write((byte)(int)(value >> 24L & 0xFFL));
output.write((byte)(int)(value >> 32L & 0xFFL));
output.write((byte)(int)(value >> 40L & 0xFFL));
output.write((byte)(int)(value >> 48L & 0xFFL));
output.write((byte)(int)(value >> 56L & 0xFFL));
}
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);
}
public static void writeSwappedFloat(OutputStream output, float value) throws IOException {
writeSwappedInteger(output, Float.floatToIntBits(value));
}
public static float readSwappedFloat(InputStream input) throws IOException {
return Float.intBitsToFloat(readSwappedInteger(input));
}
public static void writeSwappedDouble(OutputStream output, double value) throws IOException {
writeSwappedLong(output, Double.doubleToLongBits(value));
}
public static double readSwappedDouble(InputStream input) throws IOException {
return Double.longBitsToDouble(readSwappedLong(input));
}
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

@ -0,0 +1,99 @@
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;
public class FileCleaner {
static ReferenceQueue q = new ReferenceQueue();
static Collection trackers = new Vector();
static volatile boolean exitWhenFinished = false;
static Thread reaper;
public static void track(File file, Object marker) {
track(file, marker, (FileDeleteStrategy)null);
}
public static 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);
}
public static void track(String path, Object marker) {
track(path, marker, (FileDeleteStrategy)null);
}
public static void track(String path, Object marker, FileDeleteStrategy deleteStrategy) {
if (path == null)
throw new NullPointerException("The path must not be null");
addTracker(path, marker, deleteStrategy);
}
private static synchronized void addTracker(String path, Object marker, FileDeleteStrategy deleteStrategy) {
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));
}
public static int getTrackCount() {
return trackers.size();
}
public static synchronized void exitWhenFinished() {
exitWhenFinished = true;
if (reaper != null)
synchronized (reaper) {
reaper.interrupt();
}
}
static final class Reaper extends Thread {
Reaper() {
super("File Reaper");
setPriority(10);
setDaemon(true);
}
public void run() {
while (!FileCleaner.exitWhenFinished || FileCleaner.trackers.size() > 0) {
FileCleaner.Tracker tracker = null;
try {
tracker = (FileCleaner.Tracker)FileCleaner.q.remove();
} catch (Exception e) {
continue;
}
if (tracker != null) {
tracker.delete();
tracker.clear();
FileCleaner.trackers.remove(tracker);
}
}
}
}
static final class Tracker extends PhantomReference {
private final String path;
private final FileDeleteStrategy deleteStrategy;
Tracker(String path, FileDeleteStrategy deleteStrategy, Object marker, ReferenceQueue queue) {
super(marker, queue);
this.path = path;
this.deleteStrategy = (deleteStrategy == null) ? FileDeleteStrategy.NORMAL : deleteStrategy;
}
public boolean delete() {
return this.deleteStrategy.deleteQuietly(new File(this.path));
}
}
}

View file

@ -0,0 +1,50 @@
package org.apache.commons.io;
import java.io.File;
import java.io.IOException;
public class FileDeleteStrategy {
public static final FileDeleteStrategy NORMAL = new FileDeleteStrategy("Normal");
public static final FileDeleteStrategy FORCE = new ForceFileDeleteStrategy();
private final String name;
protected FileDeleteStrategy(String name) {
this.name = name;
}
public boolean deleteQuietly(File fileToDelete) {
if (fileToDelete == null || !fileToDelete.exists())
return true;
try {
return doDelete(fileToDelete);
} catch (IOException ex) {
return false;
}
}
public void delete(File fileToDelete) throws IOException {
if (fileToDelete.exists() && !doDelete(fileToDelete))
throw new IOException("Deletion failed: " + fileToDelete);
}
protected boolean doDelete(File fileToDelete) throws IOException {
return fileToDelete.delete();
}
public String toString() {
return "FileDeleteStrategy[" + this.name + "]";
}
static class ForceFileDeleteStrategy extends FileDeleteStrategy {
ForceFileDeleteStrategy() {
super("Force");
}
protected boolean doDelete(File fileToDelete) throws IOException {
FileUtils.forceDelete(fileToDelete);
return true;
}
}
}

View file

@ -0,0 +1,200 @@
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;
public class FileSystemUtils {
private static final FileSystemUtils INSTANCE = new FileSystemUtils();
private static final int INIT_PROBLEM = -1;
private static final int OTHER = 0;
private static final int WINDOWS = 1;
private static final int UNIX = 2;
private static final int POSIX_UNIX = 3;
private static final int OS;
static {
int os = 0;
try {
String osName = System.getProperty("os.name");
if (osName == null)
throw new IOException("os.name not found");
osName = osName.toLowerCase();
if (osName.indexOf("windows") != -1) {
os = 1;
} 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 = 2;
} else if (osName.indexOf("hp-ux") != -1 || osName.indexOf("aix") != -1) {
os = 3;
} else {
os = 0;
}
} catch (Exception ex) {
os = -1;
}
OS = os;
}
public static long freeSpace(String path) throws IOException {
return INSTANCE.freeSpaceOS(path, OS, false);
}
public static long freeSpaceKb(String path) throws IOException {
return INSTANCE.freeSpaceOS(path, OS, true);
}
long freeSpaceOS(String path, int os, boolean kb) throws IOException {
if (path == null)
throw new IllegalArgumentException("Path must not be empty");
switch (os) {
case 1:
return kb ? (freeSpaceWindows(path) / 1024L) : freeSpaceWindows(path);
case 2:
return freeSpaceUnix(path, kb, false);
case 3:
return freeSpaceUnix(path, kb, true);
case 0:
throw new IllegalStateException("Unsupported operating system");
}
throw new IllegalStateException("Exception caught when determining operating system");
}
long freeSpaceWindows(String path) throws IOException {
path = FilenameUtils.normalize(path);
if (path.length() > 2 && path.charAt(1) == ':')
path = path.substring(0, 2);
String[] cmdAttribs = { "cmd.exe", "/C", "dir /-c " + path };
List lines = performCommand(cmdAttribs, Integer.MAX_VALUE);
for (int i = lines.size() - 1; i >= 0; i--) {
String line = (String)lines.get(i);
if (line.length() > 0)
return parseDir(line, path);
}
throw new IOException("Command line 'dir /-c' did not return any info for path '" + path + "'");
}
long parseDir(String line, String path) throws IOException {
int bytesStart = 0;
int bytesEnd = 0;
int j = line.length() - 1;
while (j >= 0) {
char c = line.charAt(j);
if (Character.isDigit(c)) {
bytesEnd = j + 1;
break;
}
j--;
}
while (j >= 0) {
char c = line.charAt(j);
if (!Character.isDigit(c) && c != ',' && c != '.') {
bytesStart = j + 1;
break;
}
j--;
}
if (j < 0)
throw new IOException("Command line 'dir /-c' did not return valid info for path '" + path + "'");
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);
}
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);
String flags = "-";
if (kb)
flags = flags + "k";
if (posix)
flags = flags + "P";
String[] cmdAttribs = (flags.length() > 1) ? new String[] { "df", flags, path } : new String[] { "df", path };
List lines = performCommand(cmdAttribs, 3);
if (lines.size() < 2)
throw new IOException("Command line 'df' did not return info as expected for path '" + path + "'- response was " + lines);
String line2 = (String)lines.get(1);
StringTokenizer tok = new StringTokenizer(line2, " ");
if (tok.countTokens() < 4) {
if (tok.countTokens() == 1 && lines.size() >= 3) {
String line3 = (String)lines.get(2);
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();
}
tok.nextToken();
tok.nextToken();
String freeSpace = tok.nextToken();
return parseBytes(freeSpace, path);
}
long parseBytes(String freeSpace, String path) throws IOException {
try {
long bytes = Long.parseLong(freeSpace);
if (bytes < 0L)
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");
}
}
List performCommand(String[] cmdAttribs, int max) throws IOException {
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)
throw new IOException("Command line returned OS error code '" + proc.exitValue() + "' for command " + Arrays.asList(cmdAttribs));
if (lines.size() == 0)
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();
}
}
Process openProcess(String[] cmdAttribs) throws IOException {
return Runtime.getRuntime().exec(cmdAttribs);
}
}

View file

@ -0,0 +1,640 @@
package org.apache.commons.io;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.Checksum;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.FalseFileFilter;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.io.output.NullOutputStream;
public class FileUtils {
public static final long ONE_KB = 1024L;
public static final long ONE_MB = 1048576L;
public static final long ONE_GB = 1073741824L;
public static final File[] EMPTY_FILE_ARRAY = new File[0];
public static FileInputStream openInputStream(File file) throws IOException {
if (file.exists()) {
if (file.isDirectory())
throw new IOException("File '" + file + "' exists but is a directory");
if (!file.canRead())
throw new IOException("File '" + file + "' cannot be read");
} else {
throw new FileNotFoundException("File '" + file + "' does not exist");
}
return new FileInputStream(file);
}
public static FileOutputStream openOutputStream(File file) throws IOException {
if (file.exists()) {
if (file.isDirectory())
throw new IOException("File '" + file + "' exists but is a directory");
if (!file.canWrite())
throw new IOException("File '" + file + "' cannot be written to");
} else {
File parent = file.getParentFile();
if (parent != null && !parent.exists() &&
!parent.mkdirs())
throw new IOException("File '" + file + "' could not be created");
}
return new FileOutputStream(file);
}
public static String byteCountToDisplaySize(long size) {
String str;
if (size / 1073741824L > 0L) {
str = String.valueOf(size / 1073741824L) + " GB";
} else if (size / 1048576L > 0L) {
str = String.valueOf(size / 1048576L) + " MB";
} else if (size / 1024L > 0L) {
str = String.valueOf(size / 1024L) + " KB";
} else {
str = String.valueOf(size) + " bytes";
}
return str;
}
public static void touch(File file) throws IOException {
if (!file.exists()) {
OutputStream out = openOutputStream(file);
IOUtils.closeQuietly(out);
}
boolean success = file.setLastModified(System.currentTimeMillis());
if (!success)
throw new IOException("Unable to set the last modification time for " + file);
}
public static File[] convertFileCollectionToFileArray(Collection files) {
return (File[])files.toArray(new File[files.size()]);
}
private static void innerListFiles(Collection files, File directory, IOFileFilter filter) {
File[] found = directory.listFiles((FileFilter)filter);
if (found != null)
for (int i = 0; i < found.length; i++) {
if (found[i].isDirectory()) {
innerListFiles(files, found[i], filter);
} else {
files.add(found[i]);
}
}
}
public static Collection listFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) {
IOFileFilter iOFileFilter1;
if (!directory.isDirectory())
throw new IllegalArgumentException("Parameter 'directory' is not a directory");
if (fileFilter == null)
throw new NullPointerException("Parameter 'fileFilter' is null");
IOFileFilter effFileFilter = FileFilterUtils.andFileFilter(fileFilter, FileFilterUtils.notFileFilter(DirectoryFileFilter.INSTANCE));
if (dirFilter == null) {
iOFileFilter1 = FalseFileFilter.INSTANCE;
} else {
iOFileFilter1 = FileFilterUtils.andFileFilter(dirFilter, DirectoryFileFilter.INSTANCE);
}
Collection files = new LinkedList();
innerListFiles(files, directory, FileFilterUtils.orFileFilter(effFileFilter, iOFileFilter1));
return files;
}
public static Iterator iterateFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) {
return listFiles(directory, fileFilter, dirFilter).iterator();
}
private static String[] toSuffixes(String[] extensions) {
String[] suffixes = new String[extensions.length];
for (int i = 0; i < extensions.length; i++)
suffixes[i] = "." + extensions[i];
return suffixes;
}
public static Collection listFiles(File directory, String[] extensions, boolean recursive) {
IOFileFilter iOFileFilter;
if (extensions == null) {
iOFileFilter = TrueFileFilter.INSTANCE;
} else {
String[] suffixes = toSuffixes(extensions);
iOFileFilter = new SuffixFileFilter(suffixes);
}
return listFiles(directory, iOFileFilter, recursive ? TrueFileFilter.INSTANCE : FalseFileFilter.INSTANCE);
}
public static Iterator iterateFiles(File directory, String[] extensions, boolean recursive) {
return listFiles(directory, extensions, recursive).iterator();
}
public static boolean contentEquals(File file1, File file2) throws IOException {
boolean file1Exists = file1.exists();
if (file1Exists != file2.exists())
return false;
if (!file1Exists)
return true;
if (file1.isDirectory() || file2.isDirectory())
throw new IOException("Can't compare directories, only files");
if (file1.length() != file2.length())
return false;
if (file1.getCanonicalFile().equals(file2.getCanonicalFile()))
return true;
InputStream input1 = null;
InputStream input2 = null;
try {
input1 = new FileInputStream(file1);
input2 = new FileInputStream(file2);
return IOUtils.contentEquals(input1, input2);
} finally {
IOUtils.closeQuietly(input1);
IOUtils.closeQuietly(input2);
}
}
public static File toFile(URL url) {
if (url == null || !url.getProtocol().equals("file"))
return null;
String filename = url.getFile().replace('/', File.separatorChar);
int pos = 0;
while ((pos = filename.indexOf('%', pos)) >= 0) {
if (pos + 2 < filename.length()) {
String hexStr = filename.substring(pos + 1, pos + 3);
char ch = (char)Integer.parseInt(hexStr, 16);
filename = filename.substring(0, pos) + ch + filename.substring(pos + 3);
}
}
return new File(filename);
}
public static File[] toFiles(URL[] urls) {
if (urls == null || urls.length == 0)
return EMPTY_FILE_ARRAY;
File[] files = new File[urls.length];
for (int i = 0; i < urls.length; i++) {
URL url = urls[i];
if (url != null) {
if (!url.getProtocol().equals("file"))
throw new IllegalArgumentException("URL could not be converted to a File: " + url);
files[i] = toFile(url);
}
}
return files;
}
public static URL[] toURLs(File[] files) throws IOException {
URL[] urls = new URL[files.length];
for (int i = 0; i < urls.length; i++)
urls[i] = files[i].toURL();
return urls;
}
public static void copyFileToDirectory(File srcFile, File destDir) throws IOException {
copyFileToDirectory(srcFile, destDir, true);
}
public static void copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate) throws IOException {
if (destDir == null)
throw new NullPointerException("Destination must not be null");
if (destDir.exists() && !destDir.isDirectory())
throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory");
copyFile(srcFile, new File(destDir, srcFile.getName()), preserveFileDate);
}
public static void copyFile(File srcFile, File destFile) throws IOException {
copyFile(srcFile, destFile, true);
}
public static void copyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
if (srcFile == null)
throw new NullPointerException("Source must not be null");
if (destFile == null)
throw new NullPointerException("Destination must not be null");
if (!srcFile.exists())
throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
if (srcFile.isDirectory())
throw new IOException("Source '" + srcFile + "' exists but is a directory");
if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath()))
throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
if (destFile.getParentFile() != null && !destFile.getParentFile().exists() &&
!destFile.getParentFile().mkdirs())
throw new IOException("Destination '" + destFile + "' directory cannot be created");
if (destFile.exists() && !destFile.canWrite())
throw new IOException("Destination '" + destFile + "' exists but is read-only");
doCopyFile(srcFile, destFile, preserveFileDate);
}
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
if (destFile.exists() && destFile.isDirectory())
throw new IOException("Destination '" + destFile + "' exists but is a directory");
FileInputStream input = new FileInputStream(srcFile);
try {
FileOutputStream output = new FileOutputStream(destFile);
try {
IOUtils.copy(input, output);
} finally {
IOUtils.closeQuietly(output);
}
} finally {
IOUtils.closeQuietly(input);
}
if (srcFile.length() != destFile.length())
throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
if (preserveFileDate)
destFile.setLastModified(srcFile.lastModified());
}
public static void copyDirectoryToDirectory(File srcDir, File destDir) throws IOException {
if (srcDir == null)
throw new NullPointerException("Source must not be null");
if (srcDir.exists() && !srcDir.isDirectory())
throw new IllegalArgumentException("Source '" + destDir + "' is not a directory");
if (destDir == null)
throw new NullPointerException("Destination must not be null");
if (destDir.exists() && !destDir.isDirectory())
throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory");
copyDirectory(srcDir, new File(destDir, srcDir.getName()), true);
}
public static void copyDirectory(File srcDir, File destDir) throws IOException {
copyDirectory(srcDir, destDir, true);
}
public static void copyDirectory(File srcDir, File destDir, boolean preserveFileDate) throws IOException {
if (srcDir == null)
throw new NullPointerException("Source must not be null");
if (destDir == null)
throw new NullPointerException("Destination must not be null");
if (!srcDir.exists())
throw new FileNotFoundException("Source '" + srcDir + "' does not exist");
if (!srcDir.isDirectory())
throw new IOException("Source '" + srcDir + "' exists but is not a directory");
if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath()))
throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same");
doCopyDirectory(srcDir, destDir, preserveFileDate);
}
private static void doCopyDirectory(File srcDir, File destDir, boolean preserveFileDate) throws IOException {
if (destDir.exists()) {
if (!destDir.isDirectory())
throw new IOException("Destination '" + destDir + "' exists but is not a directory");
} else {
if (!destDir.mkdirs())
throw new IOException("Destination '" + destDir + "' directory cannot be created");
if (preserveFileDate)
destDir.setLastModified(srcDir.lastModified());
}
if (!destDir.canWrite())
throw new IOException("Destination '" + destDir + "' cannot be written to");
File[] files = srcDir.listFiles();
if (files == null)
throw new IOException("Failed to list contents of " + srcDir);
for (int i = 0; i < files.length; i++) {
File copiedFile = new File(destDir, files[i].getName());
if (files[i].isDirectory()) {
doCopyDirectory(files[i], copiedFile, preserveFileDate);
} else {
doCopyFile(files[i], copiedFile, preserveFileDate);
}
}
}
public static void copyURLToFile(URL source, File destination) throws IOException {
InputStream input = source.openStream();
try {
FileOutputStream output = openOutputStream(destination);
try {
IOUtils.copy(input, output);
} finally {
IOUtils.closeQuietly(output);
}
} finally {
IOUtils.closeQuietly(input);
}
}
public static void deleteDirectory(File directory) throws IOException {
if (!directory.exists())
return;
cleanDirectory(directory);
if (!directory.delete()) {
String message = "Unable to delete directory " + directory + ".";
throw new IOException(message);
}
}
public static void cleanDirectory(File directory) throws IOException {
if (!directory.exists()) {
String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
}
File[] files = directory.listFiles();
if (files == null)
throw new IOException("Failed to list contents of " + directory);
IOException exception = null;
for (int i = 0; i < files.length; i++) {
File file = files[i];
try {
forceDelete(file);
} catch (IOException ioe) {
exception = ioe = null;
}
}
if (null != exception)
throw exception;
}
public static boolean waitFor(File file, int seconds) {
int timeout = 0;
int tick = 0;
while (!file.exists()) {
if (tick++ >= 10) {
tick = 0;
if (timeout++ > seconds)
return false;
}
try {
Thread.sleep(100L);
} catch (InterruptedException ignore) {
} catch (Exception ex) {
break;
}
}
return true;
}
public static String readFileToString(File file, String encoding) throws IOException {
InputStream in = null;
try {
in = openInputStream(file);
return IOUtils.toString(in, encoding);
} finally {
IOUtils.closeQuietly(in);
}
}
public static String readFileToString(File file) throws IOException {
return readFileToString(file, null);
}
public static byte[] readFileToByteArray(File file) throws IOException {
InputStream in = null;
try {
in = openInputStream(file);
return IOUtils.toByteArray(in);
} finally {
IOUtils.closeQuietly(in);
}
}
public static List readLines(File file, String encoding) throws IOException {
InputStream in = null;
try {
in = openInputStream(file);
return IOUtils.readLines(in, encoding);
} finally {
IOUtils.closeQuietly(in);
}
}
public static List readLines(File file) throws IOException {
return readLines(file, null);
}
public static LineIterator lineIterator(File file, String encoding) throws IOException {
InputStream in = null;
try {
in = openInputStream(file);
return IOUtils.lineIterator(in, encoding);
} catch (IOException ex) {
IOUtils.closeQuietly(in);
throw ex;
} catch (RuntimeException ex) {
IOUtils.closeQuietly(in);
throw ex;
}
}
public static LineIterator lineIterator(File file) throws IOException {
return lineIterator(file, null);
}
public static void writeStringToFile(File file, String data, String encoding) throws IOException {
OutputStream out = null;
try {
out = openOutputStream(file);
IOUtils.write(data, out, encoding);
} finally {
IOUtils.closeQuietly(out);
}
}
public static void writeStringToFile(File file, String data) throws IOException {
writeStringToFile(file, data, null);
}
public static void writeByteArrayToFile(File file, byte[] data) throws IOException {
OutputStream out = null;
try {
out = openOutputStream(file);
out.write(data);
} finally {
IOUtils.closeQuietly(out);
}
}
public static void writeLines(File file, String encoding, Collection lines) throws IOException {
writeLines(file, encoding, lines, null);
}
public static void writeLines(File file, Collection lines) throws IOException {
writeLines(file, null, lines, null);
}
public static void writeLines(File file, String encoding, Collection lines, String lineEnding) throws IOException {
OutputStream out = null;
try {
out = openOutputStream(file);
IOUtils.writeLines(lines, lineEnding, out, encoding);
} finally {
IOUtils.closeQuietly(out);
}
}
public static void writeLines(File file, Collection lines, String lineEnding) throws IOException {
writeLines(file, null, lines, lineEnding);
}
public static void forceDelete(File file) throws IOException {
if (file.isDirectory()) {
deleteDirectory(file);
} else {
if (!file.exists())
throw new FileNotFoundException("File does not exist: " + file);
if (!file.delete()) {
String message = "Unable to delete file: " + file;
throw new IOException(message);
}
}
}
public static void forceDeleteOnExit(File file) throws IOException {
if (file.isDirectory()) {
deleteDirectoryOnExit(file);
} else {
file.deleteOnExit();
}
}
private static void deleteDirectoryOnExit(File directory) throws IOException {
if (!directory.exists())
return;
cleanDirectoryOnExit(directory);
directory.deleteOnExit();
}
private static void cleanDirectoryOnExit(File directory) throws IOException {
if (!directory.exists()) {
String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
}
File[] files = directory.listFiles();
if (files == null)
throw new IOException("Failed to list contents of " + directory);
IOException exception = null;
for (int i = 0; i < files.length; i++) {
File file = files[i];
try {
forceDeleteOnExit(file);
} catch (IOException ioe) {
exception = ioe = null;
}
}
if (null != exception)
throw exception;
}
public static void forceMkdir(File directory) throws IOException {
if (directory.exists()) {
if (directory.isFile()) {
String message = "File " + directory + " exists and is " + "not a directory. Unable to create directory.";
throw new IOException(message);
}
} else if (!directory.mkdirs()) {
String message = "Unable to create directory " + directory;
throw new IOException(message);
}
}
public static long sizeOfDirectory(File directory) {
if (!directory.exists()) {
String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
}
long size = 0L;
File[] files = directory.listFiles();
if (files == null)
return 0L;
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
size += sizeOfDirectory(file);
} else {
size += file.length();
}
}
return size;
}
public static boolean isFileNewer(File file, File reference) {
if (reference == null)
throw new IllegalArgumentException("No specified reference file");
if (!reference.exists())
throw new IllegalArgumentException("The reference file '" + file + "' doesn't exist");
return isFileNewer(file, reference.lastModified());
}
public static boolean isFileNewer(File file, Date date) {
if (date == null)
throw new IllegalArgumentException("No specified date");
return isFileNewer(file, date.getTime());
}
public static boolean isFileNewer(File file, long timeMillis) {
if (file == null)
throw new IllegalArgumentException("No specified file");
if (!file.exists())
return false;
return (file.lastModified() > timeMillis);
}
public static boolean isFileOlder(File file, File reference) {
if (reference == null)
throw new IllegalArgumentException("No specified reference file");
if (!reference.exists())
throw new IllegalArgumentException("The reference file '" + file + "' doesn't exist");
return isFileOlder(file, reference.lastModified());
}
public static boolean isFileOlder(File file, Date date) {
if (date == null)
throw new IllegalArgumentException("No specified date");
return isFileOlder(file, date.getTime());
}
public static boolean isFileOlder(File file, long timeMillis) {
if (file == null)
throw new IllegalArgumentException("No specified file");
if (!file.exists())
return false;
return (file.lastModified() < timeMillis);
}
public static long checksumCRC32(File file) throws IOException {
CRC32 crc = new CRC32();
checksum(file, crc);
return crc.getValue();
}
public static Checksum checksum(File file, Checksum checksum) throws IOException {
if (file.isDirectory())
throw new IllegalArgumentException("Checksums can't be computed on directories");
InputStream in = null;
try {
in = new CheckedInputStream(new FileInputStream(file), checksum);
IOUtils.copy(in, new NullOutputStream());
} finally {
IOUtils.closeQuietly(in);
}
return checksum;
}
}

View file

@ -0,0 +1,444 @@
package org.apache.commons.io;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Stack;
public class FilenameUtils {
private static final char EXTENSION_SEPARATOR = '.';
private static final char UNIX_SEPARATOR = '/';
private static final char WINDOWS_SEPARATOR = '\\';
private static final char SYSTEM_SEPARATOR = File.separatorChar;
private static final char OTHER_SEPARATOR;
static {
if (isSystemWindows()) {
OTHER_SEPARATOR = '/';
} else {
OTHER_SEPARATOR = '\\';
}
}
static boolean isSystemWindows() {
return (SYSTEM_SEPARATOR == '\\');
}
private static boolean isSeparator(char ch) {
return (ch == '/' || ch == '\\');
}
public static String normalize(String filename) {
return doNormalize(filename, true);
}
public static String normalizeNoEndSeparator(String filename) {
return doNormalize(filename, false);
}
private static String doNormalize(String filename, boolean keepSeparator) {
if (filename == null)
return null;
int size = filename.length();
if (size == 0)
return filename;
int prefix = getPrefixLength(filename);
if (prefix < 0)
return null;
char[] array = new char[size + 2];
filename.getChars(0, filename.length(), array, 0);
for (int i = 0; i < array.length; i++) {
if (array[i] == OTHER_SEPARATOR)
array[i] = SYSTEM_SEPARATOR;
}
boolean lastIsDirectory = true;
if (array[size - 1] != SYSTEM_SEPARATOR) {
array[size++] = SYSTEM_SEPARATOR;
lastIsDirectory = false;
}
for (int j = prefix + 1; j < size; j++) {
if (array[j] == SYSTEM_SEPARATOR && array[j - 1] == SYSTEM_SEPARATOR) {
System.arraycopy(array, j, array, j - 1, size - j);
size--;
j--;
}
}
for (int k = prefix + 1; k < size; k++) {
if (array[k] == SYSTEM_SEPARATOR && array[k - 1] == '.' && (k == prefix + 1 || array[k - 2] == SYSTEM_SEPARATOR)) {
if (k == size - 1)
lastIsDirectory = true;
System.arraycopy(array, k + 1, array, k - 1, size - k);
size -= 2;
k--;
}
}
for (int m = prefix + 2; m < size; m++) {
if (array[m] == SYSTEM_SEPARATOR && array[m - 1] == '.' && array[m - 2] == '.' && (m == prefix + 2 || array[m - 3] == SYSTEM_SEPARATOR)) {
if (m == prefix + 2)
return null;
if (m == size - 1)
lastIsDirectory = true;
int n = m - 4;
while (true) {
if (n < prefix) {
System.arraycopy(array, m + 1, array, prefix, size - m);
size -= m + 1 - prefix;
m = prefix + 1;
break;
}
if (array[n] == SYSTEM_SEPARATOR) {
System.arraycopy(array, m + 1, array, n + 1, size - m);
size -= m - n;
m = n + 1;
break;
}
n--;
}
}
}
if (size <= 0)
return "";
if (size <= prefix)
return new String(array, 0, size);
if (lastIsDirectory && keepSeparator)
return new String(array, 0, size);
return new String(array, 0, size - 1);
}
public static String concat(String basePath, String fullFilenameToAdd) {
int prefix = getPrefixLength(fullFilenameToAdd);
if (prefix < 0)
return null;
if (prefix > 0)
return normalize(fullFilenameToAdd);
if (basePath == null)
return null;
int len = basePath.length();
if (len == 0)
return normalize(fullFilenameToAdd);
char ch = basePath.charAt(len - 1);
if (isSeparator(ch))
return normalize(basePath + fullFilenameToAdd);
return normalize(basePath + '/' + fullFilenameToAdd);
}
public static String separatorsToUnix(String path) {
if (path == null || path.indexOf('\\') == -1)
return path;
return path.replace('\\', '/');
}
public static String separatorsToWindows(String path) {
if (path == null || path.indexOf('/') == -1)
return path;
return path.replace('/', '\\');
}
public static String separatorsToSystem(String path) {
if (path == null)
return null;
if (isSystemWindows())
return separatorsToWindows(path);
return separatorsToUnix(path);
}
public static int getPrefixLength(String filename) {
if (filename == null)
return -1;
int len = filename.length();
if (len == 0)
return 0;
char ch0 = filename.charAt(0);
if (ch0 == ':')
return -1;
if (len == 1) {
if (ch0 == '~')
return 2;
return isSeparator(ch0) ? 1 : 0;
}
if (ch0 == '~') {
int posUnix = filename.indexOf('/', 1);
int posWin = filename.indexOf('\\', 1);
if (posUnix == -1 && posWin == -1)
return len + 1;
posUnix = (posUnix == -1) ? posWin : posUnix;
posWin = (posWin == -1) ? posUnix : posWin;
return Math.min(posUnix, posWin) + 1;
}
char ch1 = filename.charAt(1);
if (ch1 == ':') {
ch0 = Character.toUpperCase(ch0);
if (ch0 >= 'A' && ch0 <= 'Z') {
if (len == 2 || !isSeparator(filename.charAt(2)))
return 2;
return 3;
}
return -1;
}
if (isSeparator(ch0) && isSeparator(ch1)) {
int posUnix = filename.indexOf('/', 2);
int posWin = filename.indexOf('\\', 2);
if ((posUnix == -1 && posWin == -1) || posUnix == 2 || posWin == 2)
return -1;
posUnix = (posUnix == -1) ? posWin : posUnix;
posWin = (posWin == -1) ? posUnix : posWin;
return Math.min(posUnix, posWin) + 1;
}
return isSeparator(ch0) ? 1 : 0;
}
public static int indexOfLastSeparator(String filename) {
if (filename == null)
return -1;
int lastUnixPos = filename.lastIndexOf('/');
int lastWindowsPos = filename.lastIndexOf('\\');
return Math.max(lastUnixPos, lastWindowsPos);
}
public static int indexOfExtension(String filename) {
if (filename == null)
return -1;
int extensionPos = filename.lastIndexOf('.');
int lastSeparator = indexOfLastSeparator(filename);
return (lastSeparator > extensionPos) ? -1 : extensionPos;
}
public static String getPrefix(String filename) {
if (filename == null)
return null;
int len = getPrefixLength(filename);
if (len < 0)
return null;
if (len > filename.length())
return filename + '/';
return filename.substring(0, len);
}
public static String getPath(String filename) {
return doGetPath(filename, 1);
}
public static String getPathNoEndSeparator(String filename) {
return doGetPath(filename, 0);
}
private static String doGetPath(String filename, int separatorAdd) {
if (filename == null)
return null;
int prefix = getPrefixLength(filename);
if (prefix < 0)
return null;
int index = indexOfLastSeparator(filename);
if (prefix >= filename.length() || index < 0)
return "";
return filename.substring(prefix, index + separatorAdd);
}
public static String getFullPath(String filename) {
return doGetFullPath(filename, true);
}
public static String getFullPathNoEndSeparator(String filename) {
return doGetFullPath(filename, false);
}
private static String doGetFullPath(String filename, boolean includeSeparator) {
if (filename == null)
return null;
int prefix = getPrefixLength(filename);
if (prefix < 0)
return null;
if (prefix >= filename.length()) {
if (includeSeparator)
return getPrefix(filename);
return filename;
}
int index = indexOfLastSeparator(filename);
if (index < 0)
return filename.substring(0, prefix);
int end = index + (includeSeparator ? 1 : 0);
return filename.substring(0, end);
}
public static String getName(String filename) {
if (filename == null)
return null;
int index = indexOfLastSeparator(filename);
return filename.substring(index + 1);
}
public static String getBaseName(String filename) {
return removeExtension(getName(filename));
}
public static String getExtension(String filename) {
if (filename == null)
return null;
int index = indexOfExtension(filename);
if (index == -1)
return "";
return filename.substring(index + 1);
}
public static String removeExtension(String filename) {
if (filename == null)
return null;
int index = indexOfExtension(filename);
if (index == -1)
return filename;
return filename.substring(0, index);
}
public static boolean equals(String filename1, String filename2) {
return equals(filename1, filename2, false, IOCase.SENSITIVE);
}
public static boolean equalsOnSystem(String filename1, String filename2) {
return equals(filename1, filename2, false, IOCase.SYSTEM);
}
public static boolean equalsNormalized(String filename1, String filename2) {
return equals(filename1, filename2, true, IOCase.SENSITIVE);
}
public static boolean equalsNormalizedOnSystem(String filename1, String filename2) {
return equals(filename1, filename2, true, IOCase.SYSTEM);
}
public static boolean equals(String filename1, String filename2, boolean normalized, IOCase caseSensitivity) {
if (filename1 == null || filename2 == null)
return (filename1 == filename2);
if (normalized) {
filename1 = normalize(filename1);
filename2 = normalize(filename2);
}
if (caseSensitivity == null)
caseSensitivity = IOCase.SENSITIVE;
return caseSensitivity.checkEquals(filename1, filename2);
}
public static boolean isExtension(String filename, String extension) {
if (filename == null)
return false;
if (extension == null || extension.length() == 0)
return (indexOfExtension(filename) == -1);
String fileExt = getExtension(filename);
return fileExt.equals(extension);
}
public static boolean isExtension(String filename, String[] extensions) {
if (filename == null)
return false;
if (extensions == null || extensions.length == 0)
return (indexOfExtension(filename) == -1);
String fileExt = getExtension(filename);
for (int i = 0; i < extensions.length; i++) {
if (fileExt.equals(extensions[i]))
return true;
}
return false;
}
public static boolean isExtension(String filename, Collection extensions) {
if (filename == null)
return false;
if (extensions == null || extensions.isEmpty())
return (indexOfExtension(filename) == -1);
String fileExt = getExtension(filename);
for (Iterator it = extensions.iterator(); it.hasNext();) {
if (fileExt.equals(it.next()))
return true;
}
return false;
}
public static boolean wildcardMatch(String filename, String wildcardMatcher) {
return wildcardMatch(filename, wildcardMatcher, IOCase.SENSITIVE);
}
public static boolean wildcardMatchOnSystem(String filename, String wildcardMatcher) {
return wildcardMatch(filename, wildcardMatcher, IOCase.SYSTEM);
}
public static boolean wildcardMatch(String filename, String wildcardMatcher, IOCase caseSensitivity) {
if (filename == null && wildcardMatcher == null)
return true;
if (filename == null || wildcardMatcher == null)
return false;
if (caseSensitivity == null)
caseSensitivity = IOCase.SENSITIVE;
filename = caseSensitivity.convertCase(filename);
wildcardMatcher = caseSensitivity.convertCase(wildcardMatcher);
String[] wcs = splitOnTokens(wildcardMatcher);
boolean anyChars = false;
int textIdx = 0;
int wcsIdx = 0;
Stack backtrack = new Stack();
do {
if (backtrack.size() > 0) {
int[] array = (int[])backtrack.pop();
wcsIdx = array[0];
textIdx = array[1];
anyChars = true;
}
while (wcsIdx < wcs.length) {
if (wcs[wcsIdx].equals("?")) {
textIdx++;
anyChars = false;
} else if (wcs[wcsIdx].equals("*")) {
anyChars = true;
if (wcsIdx == wcs.length - 1)
textIdx = filename.length();
} else {
if (anyChars) {
textIdx = filename.indexOf(wcs[wcsIdx], textIdx);
if (textIdx == -1)
break;
int repeat = filename.indexOf(wcs[wcsIdx], textIdx + 1);
if (repeat >= 0)
backtrack.push(new int[] { wcsIdx, repeat });
} else if (!filename.startsWith(wcs[wcsIdx], textIdx)) {
break;
}
textIdx += wcs[wcsIdx].length();
anyChars = false;
}
wcsIdx++;
}
if (wcsIdx == wcs.length && textIdx == filename.length())
return true;
} while (backtrack.size() > 0);
return false;
}
static String[] splitOnTokens(String text) {
if (text.indexOf("?") == -1 && text.indexOf("*") == -1)
return new String[] { text };
char[] array = text.toCharArray();
ArrayList list = new ArrayList();
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < array.length; i++) {
if (array[i] == '?' || array[i] == '*') {
if (buffer.length() != 0) {
list.add(buffer.toString());
buffer.setLength(0);
}
if (array[i] == '?') {
list.add("?");
} else if (list.size() == 0 || (i > 0 && !list.get(list.size() - 1).equals("*"))) {
list.add("*");
}
} else {
buffer.append(array[i]);
}
}
if (buffer.length() != 0)
list.add(buffer.toString());
return (String[])list.toArray(new String[list.size()]);
}
}

View file

@ -0,0 +1,67 @@
package org.apache.commons.io;
import java.io.IOException;
import java.io.OutputStream;
public class HexDump {
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 + (long)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;
buffer.append((Object)dump(display_offset)).append(' ');
for (int k = 0; k < 16; k++) {
if (k < chars_read) {
buffer.append((Object)dump(data[k + j]));
} else {
buffer.append(" ");
}
buffer.append(' ');
}
for (int i = 0; i < chars_read; i++) {
if (data[i + j] >= 32 && data[i + j] < Byte.MAX_VALUE) {
buffer.append((char)data[i + j]);
} else {
buffer.append('.');
}
}
buffer.append(EOL);
stream.write(buffer.toString().getBytes());
stream.flush();
buffer.setLength(0);
display_offset += (long)chars_read;
}
}
public static final String EOL = System.getProperty("line.separator");
private static final StringBuffer _lbuffer = new StringBuffer(8);
private static final StringBuffer _cbuffer = new StringBuffer(2);
private static final char[] _hexcodes = new char[] {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F' };
private static final int[] _shifts = new int[] { 28, 24, 20, 16, 12, 8, 4, 0 };
private static StringBuffer dump(long value) {
_lbuffer.setLength(0);
for (int j = 0; j < 8; j++)
_lbuffer.append(_hexcodes[(int)(value >> _shifts[j]) & 0xF]);
return _lbuffer;
}
private static StringBuffer dump(byte value) {
_cbuffer.setLength(0);
for (int j = 0; j < 2; j++)
_cbuffer.append(_hexcodes[value >> _shifts[j + 6] & 0xF]);
return _cbuffer;
}
}

View file

@ -0,0 +1,73 @@
package org.apache.commons.io;
import java.io.Serializable;
public final class IOCase implements Serializable {
public static final IOCase SENSITIVE = new IOCase("Sensitive", true);
public static final IOCase INSENSITIVE = new IOCase("Insensitive", false);
public static final IOCase SYSTEM = new IOCase("System", !FilenameUtils.isSystemWindows());
private static final long serialVersionUID = -6343169151696340687L;
private final String name;
private final transient boolean sensitive;
public static IOCase forName(String name) {
if (SENSITIVE.name.equals(name))
return SENSITIVE;
if (INSENSITIVE.name.equals(name))
return INSENSITIVE;
if (SYSTEM.name.equals(name))
return SYSTEM;
throw new IllegalArgumentException("Invalid IOCase name: " + name);
}
private IOCase(String name, boolean sensitive) {
this.name = name;
this.sensitive = sensitive;
}
private Object readResolve() {
return forName(this.name);
}
public String getName() {
return this.name;
}
public boolean isCaseSensitive() {
return this.sensitive;
}
public boolean checkEquals(String str1, String str2) {
if (str1 == null || str2 == null)
throw new NullPointerException("The strings must not be null");
return this.sensitive ? str1.equals(str2) : str1.equalsIgnoreCase(str2);
}
public boolean checkStartsWith(String str, String start) {
return str.regionMatches(!this.sensitive, 0, start, 0, start.length());
}
public boolean checkEndsWith(String str, String end) {
int endLen = end.length();
return str.regionMatches(!this.sensitive, str.length() - endLen, end, 0, endLen);
}
public boolean checkRegionMatches(String str, int strStartIndex, String search) {
return str.regionMatches(!this.sensitive, strStartIndex, search, 0, search.length());
}
String convertCase(String str) {
if (str == null)
return null;
return this.sensitive ? str : str.toLowerCase();
}
public String toString() {
return this.name;
}
}

View file

@ -0,0 +1,404 @@
package org.apache.commons.io;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.io.output.ByteArrayOutputStream;
public class IOUtils {
public static final char DIR_SEPARATOR_UNIX = '/';
public static final char DIR_SEPARATOR_WINDOWS = '\\';
public static final char DIR_SEPARATOR = File.separatorChar;
public static final String LINE_SEPARATOR_UNIX = "\n";
public static final String LINE_SEPARATOR_WINDOWS = "\r\n";
public static final String LINE_SEPARATOR;
private static final int DEFAULT_BUFFER_SIZE = 4096;
static {
StringWriter buf = new StringWriter(4);
PrintWriter out = new PrintWriter(buf);
out.println();
LINE_SEPARATOR = buf.toString();
}
public static void closeQuietly(Reader input) {
try {
if (input != null)
input.close();
} catch (IOException ioe) {}
}
public static void closeQuietly(Writer output) {
try {
if (output != null)
output.close();
} catch (IOException ioe) {}
}
public static void closeQuietly(InputStream input) {
try {
if (input != null)
input.close();
} catch (IOException ioe) {}
}
public static void closeQuietly(OutputStream output) {
try {
if (output != null)
output.close();
} catch (IOException ioe) {}
}
public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(input, output);
return output.toByteArray();
}
public static byte[] toByteArray(Reader input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(input, output);
return output.toByteArray();
}
public static byte[] toByteArray(Reader input, String encoding) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(input, output, encoding);
return output.toByteArray();
}
public static byte[] toByteArray(String input) throws IOException {
return input.getBytes();
}
public static char[] toCharArray(InputStream is) throws IOException {
CharArrayWriter output = new CharArrayWriter();
copy(is, output);
return output.toCharArray();
}
public static char[] toCharArray(InputStream is, String encoding) throws IOException {
CharArrayWriter output = new CharArrayWriter();
copy(is, output, encoding);
return output.toCharArray();
}
public static char[] toCharArray(Reader input) throws IOException {
CharArrayWriter sw = new CharArrayWriter();
copy(input, sw);
return sw.toCharArray();
}
public static String toString(InputStream input) throws IOException {
StringWriter sw = new StringWriter();
copy(input, sw);
return sw.toString();
}
public static String toString(InputStream input, String encoding) throws IOException {
StringWriter sw = new StringWriter();
copy(input, sw, encoding);
return sw.toString();
}
public static String toString(Reader input) throws IOException {
StringWriter sw = new StringWriter();
copy(input, sw);
return sw.toString();
}
public static String toString(byte[] input) throws IOException {
return new String(input);
}
public static String toString(byte[] input, String encoding) throws IOException {
if (encoding == null)
return new String(input);
return new String(input, encoding);
}
public static List readLines(InputStream input) throws IOException {
InputStreamReader reader = new InputStreamReader(input);
return readLines(reader);
}
public static List readLines(InputStream input, String encoding) throws IOException {
if (encoding == null)
return readLines(input);
InputStreamReader reader = new InputStreamReader(input, encoding);
return readLines(reader);
}
public static List readLines(Reader input) throws IOException {
BufferedReader reader = new BufferedReader(input);
List list = new ArrayList();
String line = reader.readLine();
while (line != null) {
list.add(line);
line = reader.readLine();
}
return list;
}
public static LineIterator lineIterator(Reader reader) {
return new LineIterator(reader);
}
public static LineIterator lineIterator(InputStream input, String encoding) throws IOException {
Reader reader = null;
if (encoding == null) {
reader = new InputStreamReader(input);
} else {
reader = new InputStreamReader(input, encoding);
}
return new LineIterator(reader);
}
public static InputStream toInputStream(String input) {
byte[] bytes = input.getBytes();
return new ByteArrayInputStream(bytes);
}
public static InputStream toInputStream(String input, String encoding) throws IOException {
byte[] bytes = (encoding != null) ? input.getBytes(encoding) : input.getBytes();
return new ByteArrayInputStream(bytes);
}
public static void write(byte[] data, OutputStream output) throws IOException {
if (data != null)
output.write(data);
}
public static void write(byte[] data, Writer output) throws IOException {
if (data != null)
output.write(new String(data));
}
public static void write(byte[] data, Writer output, String encoding) throws IOException {
if (data != null)
if (encoding == null) {
write(data, output);
} else {
output.write(new String(data, encoding));
}
}
public static void write(char[] data, Writer output) throws IOException {
if (data != null)
output.write(data);
}
public static void write(char[] data, OutputStream output) throws IOException {
if (data != null)
output.write(new String(data).getBytes());
}
public static void write(char[] data, OutputStream output, String encoding) throws IOException {
if (data != null)
if (encoding == null) {
write(data, output);
} else {
output.write(new String(data).getBytes(encoding));
}
}
public static void write(String data, Writer output) throws IOException {
if (data != null)
output.write(data);
}
public static void write(String data, OutputStream output) throws IOException {
if (data != null)
output.write(data.getBytes());
}
public static void write(String data, OutputStream output, String encoding) throws IOException {
if (data != null)
if (encoding == null) {
write(data, output);
} else {
output.write(data.getBytes(encoding));
}
}
public static void write(StringBuffer data, Writer output) throws IOException {
if (data != null)
output.write(data.toString());
}
public static void write(StringBuffer data, OutputStream output) throws IOException {
if (data != null)
output.write(data.toString().getBytes());
}
public static void write(StringBuffer data, OutputStream output, String encoding) throws IOException {
if (data != null)
if (encoding == null) {
write(data, output);
} else {
output.write(data.toString().getBytes(encoding));
}
}
public static void writeLines(Collection lines, String lineEnding, OutputStream output) throws IOException {
if (lines == null)
return;
if (lineEnding == null)
lineEnding = LINE_SEPARATOR;
for (Iterator it = lines.iterator(); it.hasNext(); ) {
Object line = it.next();
if (line != null)
output.write(line.toString().getBytes());
output.write(lineEnding.getBytes());
}
}
public static void writeLines(Collection lines, String lineEnding, OutputStream output, String encoding) throws IOException {
if (encoding == null) {
writeLines(lines, lineEnding, output);
} else {
if (lines == null)
return;
if (lineEnding == null)
lineEnding = LINE_SEPARATOR;
for (Iterator it = lines.iterator(); it.hasNext(); ) {
Object line = it.next();
if (line != null)
output.write(line.toString().getBytes(encoding));
output.write(lineEnding.getBytes(encoding));
}
}
}
public static void writeLines(Collection lines, String lineEnding, Writer writer) throws IOException {
if (lines == null)
return;
if (lineEnding == null)
lineEnding = LINE_SEPARATOR;
for (Iterator it = lines.iterator(); it.hasNext(); ) {
Object line = it.next();
if (line != null)
writer.write(line.toString());
writer.write(lineEnding);
}
}
public static int copy(InputStream input, OutputStream output) throws IOException {
long count = copyLarge(input, output);
if (count > Integer.MAX_VALUE)
return -1;
return (int)count;
}
public static long copyLarge(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[4096];
long count = 0L;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += (long)n;
}
return count;
}
public static void copy(InputStream input, Writer output) throws IOException {
InputStreamReader in = new InputStreamReader(input);
copy(in, output);
}
public static void copy(InputStream input, Writer output, String encoding) throws IOException {
if (encoding == null) {
copy(input, output);
} else {
InputStreamReader in = new InputStreamReader(input, encoding);
copy(in, output);
}
}
public static int copy(Reader input, Writer output) throws IOException {
long count = copyLarge(input, output);
if (count > Integer.MAX_VALUE)
return -1;
return (int)count;
}
public static long copyLarge(Reader input, Writer output) throws IOException {
char[] buffer = new char[4096];
long count = 0L;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += (long)n;
}
return count;
}
public static void copy(Reader input, OutputStream output) throws IOException {
OutputStreamWriter out = new OutputStreamWriter(output);
copy(input, out);
out.flush();
}
public static void copy(Reader input, OutputStream output, String encoding) throws IOException {
if (encoding == null) {
copy(input, output);
} else {
OutputStreamWriter out = new OutputStreamWriter(output, encoding);
copy(input, out);
out.flush();
}
}
public static boolean contentEquals(InputStream input1, InputStream input2) throws IOException {
if (!(input1 instanceof BufferedInputStream))
input1 = new BufferedInputStream(input1);
if (!(input2 instanceof BufferedInputStream))
input2 = new BufferedInputStream(input2);
int ch = input1.read();
while (-1 != ch) {
int i = input2.read();
if (ch != i)
return false;
ch = input1.read();
}
int ch2 = input2.read();
return (ch2 == -1);
}
public static boolean contentEquals(Reader input1, Reader input2) throws IOException {
if (!(input1 instanceof BufferedReader))
input1 = new BufferedReader(input1);
if (!(input2 instanceof BufferedReader))
input2 = new BufferedReader(input2);
int ch = input1.read();
while (-1 != ch) {
int i = input2.read();
if (ch != i)
return false;
ch = input1.read();
}
int ch2 = input2.read();
return (ch2 == -1);
}
}

View file

@ -0,0 +1,79 @@
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;
public class LineIterator implements Iterator {
private final BufferedReader bufferedReader;
private String cachedLine;
private boolean finished = false;
public LineIterator(Reader reader) throws IllegalArgumentException {
if (reader == null)
throw new IllegalArgumentException("Reader must not be null");
if (reader instanceof BufferedReader) {
this.bufferedReader = (BufferedReader)reader;
} else {
this.bufferedReader = new BufferedReader(reader);
}
}
public boolean hasNext() {
if (this.cachedLine != null)
return true;
if (this.finished)
return false;
try {
while (true) {
String line = this.bufferedReader.readLine();
if (line == null) {
this.finished = true;
return false;
}
if (isValidLine(line)) {
this.cachedLine = line;
return true;
}
}
} catch (IOException ioe) {
close();
throw new IllegalStateException(ioe.toString());
}
}
protected boolean isValidLine(String line) {
return true;
}
public Object next() {
return nextLine();
}
public String nextLine() {
if (!hasNext())
throw new NoSuchElementException("No more lines");
String currentLine = this.cachedLine;
this.cachedLine = null;
return currentLine;
}
public void close() {
this.finished = true;
IOUtils.closeQuietly(this.bufferedReader);
this.cachedLine = null;
}
public void remove() {
throw new UnsupportedOperationException("Remove unsupported on LineIterator");
}
public static void closeQuietly(LineIterator iterator) {
if (iterator != null)
iterator.close();
}
}

View file

@ -0,0 +1,13 @@
package org.apache.commons.io.filefilter;
import java.io.File;
public abstract class AbstractFileFilter implements IOFileFilter {
public boolean accept(File file) {
return accept(file.getParentFile(), file.getName());
}
public boolean accept(File dir, String name) {
return accept(new File(dir, name));
}
}

View file

@ -0,0 +1,41 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.util.Date;
import org.apache.commons.io.FileUtils;
public class AgeFileFilter extends AbstractFileFilter {
private long cutoff;
private boolean acceptOlder;
public AgeFileFilter(long cutoff) {
this(cutoff, true);
}
public AgeFileFilter(long cutoff, boolean acceptOlder) {
this.acceptOlder = acceptOlder;
this.cutoff = cutoff;
}
public AgeFileFilter(Date cutoffDate) {
this(cutoffDate, true);
}
public AgeFileFilter(Date cutoffDate, boolean acceptOlder) {
this(cutoffDate.getTime(), acceptOlder);
}
public AgeFileFilter(File cutoffReference) {
this(cutoffReference, true);
}
public AgeFileFilter(File cutoffReference, boolean acceptOlder) {
this(cutoffReference.lastModified(), acceptOlder);
}
public boolean accept(File file) {
boolean newer = FileUtils.isFileNewer(file, this.cutoff);
return this.acceptOlder ? (!newer) : newer;
}
}

View file

@ -0,0 +1,69 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class AndFileFilter extends AbstractFileFilter implements ConditionalFileFilter {
private List fileFilters;
public AndFileFilter() {
this.fileFilters = new ArrayList();
}
public AndFileFilter(List fileFilters) {
if (fileFilters == null) {
this.fileFilters = new ArrayList();
} else {
this.fileFilters = new ArrayList(fileFilters);
}
}
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);
}
public void addFileFilter(IOFileFilter ioFileFilter) {
this.fileFilters.add(ioFileFilter);
}
public List getFileFilters() {
return Collections.unmodifiableList(this.fileFilters);
}
public boolean removeFileFilter(IOFileFilter ioFileFilter) {
return this.fileFilters.remove(ioFileFilter);
}
public void setFileFilters(List fileFilters) {
this.fileFilters = new ArrayList(fileFilters);
}
public boolean accept(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;
}
public boolean accept(File file, 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;
}
}

View file

@ -0,0 +1,15 @@
package org.apache.commons.io.filefilter;
import java.io.File;
public class CanReadFileFilter extends AbstractFileFilter {
public static final IOFileFilter CAN_READ = new CanReadFileFilter();
public static final IOFileFilter CANNOT_READ = new NotFileFilter(CAN_READ);
public static final IOFileFilter READ_ONLY = new AndFileFilter(CAN_READ, CanWriteFileFilter.CANNOT_WRITE);
public boolean accept(File file) {
return file.canRead();
}
}

View file

@ -0,0 +1,13 @@
package org.apache.commons.io.filefilter;
import java.io.File;
public class CanWriteFileFilter extends AbstractFileFilter {
public static final IOFileFilter CAN_WRITE = new CanWriteFileFilter();
public static final IOFileFilter CANNOT_WRITE = new NotFileFilter(CAN_WRITE);
public boolean accept(File file) {
return file.canWrite();
}
}

View file

@ -0,0 +1,13 @@
package org.apache.commons.io.filefilter;
import java.util.List;
public interface ConditionalFileFilter {
void addFileFilter(IOFileFilter paramIOFileFilter);
List getFileFilters();
boolean removeFileFilter(IOFileFilter paramIOFileFilter);
void setFileFilters(List paramList);
}

View file

@ -0,0 +1,35 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
public class DelegateFileFilter extends AbstractFileFilter {
private FilenameFilter filenameFilter;
private FileFilter fileFilter;
public DelegateFileFilter(FilenameFilter filter) {
if (filter == null)
throw new IllegalArgumentException("The FilenameFilter must not be null");
this.filenameFilter = filter;
}
public DelegateFileFilter(FileFilter filter) {
if (filter == null)
throw new IllegalArgumentException("The FileFilter must not be null");
this.fileFilter = filter;
}
public boolean accept(File file) {
if (this.fileFilter != null)
return this.fileFilter.accept(file);
return super.accept(file);
}
public boolean accept(File dir, String name) {
if (this.filenameFilter != null)
return this.filenameFilter.accept(dir, name);
return super.accept(dir, name);
}
}

View file

@ -0,0 +1,13 @@
package org.apache.commons.io.filefilter;
import java.io.File;
public class DirectoryFileFilter extends AbstractFileFilter {
public static final IOFileFilter DIRECTORY = new DirectoryFileFilter();
public static final IOFileFilter INSTANCE = DIRECTORY;
public boolean accept(File file) {
return file.isDirectory();
}
}

View file

@ -0,0 +1,17 @@
package org.apache.commons.io.filefilter;
import java.io.File;
public class EmptyFileFilter extends AbstractFileFilter {
public static final IOFileFilter EMPTY = new EmptyFileFilter();
public static final IOFileFilter NOT_EMPTY = new NotFileFilter(EMPTY);
public boolean accept(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
return (files == null || files.length == 0);
}
return (file.length() == 0L);
}
}

View file

@ -0,0 +1,17 @@
package org.apache.commons.io.filefilter;
import java.io.File;
public class FalseFileFilter implements IOFileFilter {
public static final IOFileFilter FALSE = new FalseFileFilter();
public static final IOFileFilter INSTANCE = FALSE;
public boolean accept(File file) {
return false;
}
public boolean accept(File dir, String name) {
return false;
}
}

View file

@ -0,0 +1,11 @@
package org.apache.commons.io.filefilter;
import java.io.File;
public class FileFileFilter extends AbstractFileFilter {
public static final IOFileFilter FILE = new FileFileFilter();
public boolean accept(File file) {
return file.isFile();
}
}

View file

@ -0,0 +1,126 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.util.Date;
public class FileFilterUtils {
private static IOFileFilter cvsFilter;
private static IOFileFilter svnFilter;
public static IOFileFilter prefixFileFilter(String prefix) {
return new PrefixFileFilter(prefix);
}
public static IOFileFilter suffixFileFilter(String suffix) {
return new SuffixFileFilter(suffix);
}
public static IOFileFilter nameFileFilter(String name) {
return new NameFileFilter(name);
}
public static IOFileFilter directoryFileFilter() {
return DirectoryFileFilter.DIRECTORY;
}
public static IOFileFilter fileFileFilter() {
return FileFileFilter.FILE;
}
public static IOFileFilter andFileFilter(IOFileFilter filter1, IOFileFilter filter2) {
return new AndFileFilter(filter1, filter2);
}
public static IOFileFilter orFileFilter(IOFileFilter filter1, IOFileFilter filter2) {
return new OrFileFilter(filter1, filter2);
}
public static IOFileFilter notFileFilter(IOFileFilter filter) {
return new NotFileFilter(filter);
}
public static IOFileFilter trueFileFilter() {
return TrueFileFilter.TRUE;
}
public static IOFileFilter falseFileFilter() {
return FalseFileFilter.FALSE;
}
public static IOFileFilter asFileFilter(FileFilter filter) {
return new DelegateFileFilter(filter);
}
public static IOFileFilter asFileFilter(FilenameFilter filter) {
return new DelegateFileFilter(filter);
}
public static IOFileFilter ageFileFilter(long cutoff) {
return new AgeFileFilter(cutoff);
}
public static IOFileFilter ageFileFilter(long cutoff, boolean acceptOlder) {
return new AgeFileFilter(cutoff, acceptOlder);
}
public static IOFileFilter ageFileFilter(Date cutoffDate) {
return new AgeFileFilter(cutoffDate);
}
public static IOFileFilter ageFileFilter(Date cutoffDate, boolean acceptOlder) {
return new AgeFileFilter(cutoffDate, acceptOlder);
}
public static IOFileFilter ageFileFilter(File cutoffReference) {
return new AgeFileFilter(cutoffReference);
}
public static IOFileFilter ageFileFilter(File cutoffReference, boolean acceptOlder) {
return new AgeFileFilter(cutoffReference, acceptOlder);
}
public static IOFileFilter sizeFileFilter(long threshold) {
return new SizeFileFilter(threshold);
}
public static IOFileFilter sizeFileFilter(long threshold, boolean acceptLarger) {
return new SizeFileFilter(threshold, acceptLarger);
}
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);
}
public static IOFileFilter makeCVSAware(IOFileFilter filter) {
if (cvsFilter == null)
cvsFilter = notFileFilter(andFileFilter(directoryFileFilter(), nameFileFilter("CVS")));
if (filter == null)
return cvsFilter;
return andFileFilter(filter, cvsFilter);
}
public static IOFileFilter makeSVNAware(IOFileFilter filter) {
if (svnFilter == null)
svnFilter = notFileFilter(andFileFilter(directoryFileFilter(), nameFileFilter(".svn")));
if (filter == null)
return svnFilter;
return andFileFilter(filter, svnFilter);
}
public static IOFileFilter makeDirectoryOnly(IOFileFilter filter) {
if (filter == null)
return DirectoryFileFilter.DIRECTORY;
return new AndFileFilter(DirectoryFileFilter.DIRECTORY, filter);
}
public static IOFileFilter makeFileOnly(IOFileFilter filter) {
if (filter == null)
return FileFileFilter.FILE;
return new AndFileFilter(FileFileFilter.FILE, filter);
}
}

View file

@ -0,0 +1,13 @@
package org.apache.commons.io.filefilter;
import java.io.File;
public class HiddenFileFilter extends AbstractFileFilter {
public static final IOFileFilter HIDDEN = new HiddenFileFilter();
public static final IOFileFilter VISIBLE = new NotFileFilter(HIDDEN);
public boolean accept(File file) {
return file.isHidden();
}
}

View file

@ -0,0 +1,11 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
public interface IOFileFilter extends FileFilter, FilenameFilter {
boolean accept(File paramFile);
boolean accept(File paramFile, String paramString);
}

View file

@ -0,0 +1,61 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.util.List;
import org.apache.commons.io.IOCase;
public class NameFileFilter extends AbstractFileFilter {
private String[] names;
private IOCase caseSensitivity;
public NameFileFilter(String name) {
this(name, 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;
}
public NameFileFilter(String[] names) {
this(names, 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;
}
public NameFileFilter(List names) {
this(names, null);
}
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;
}
public boolean accept(File file) {
String name = file.getName();
for (int i = 0; i < this.names.length; i++) {
if (this.caseSensitivity.checkEquals(name, this.names[i]))
return true;
}
return false;
}
public boolean accept(File file, String name) {
for (int i = 0; i < this.names.length; i++) {
if (this.caseSensitivity.checkEquals(name, this.names[i]))
return true;
}
return false;
}
}

View file

@ -0,0 +1,21 @@
package org.apache.commons.io.filefilter;
import java.io.File;
public class NotFileFilter extends AbstractFileFilter {
private IOFileFilter filter;
public NotFileFilter(IOFileFilter filter) {
if (filter == null)
throw new IllegalArgumentException("The filter must not be null");
this.filter = filter;
}
public boolean accept(File file) {
return !this.filter.accept(file);
}
public boolean accept(File file, String name) {
return !this.filter.accept(file, name);
}
}

View file

@ -0,0 +1,65 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class OrFileFilter extends AbstractFileFilter implements ConditionalFileFilter {
private List fileFilters;
public OrFileFilter() {
this.fileFilters = new ArrayList();
}
public OrFileFilter(List fileFilters) {
if (fileFilters == null) {
this.fileFilters = new ArrayList();
} else {
this.fileFilters = new ArrayList(fileFilters);
}
}
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);
}
public void addFileFilter(IOFileFilter ioFileFilter) {
this.fileFilters.add(ioFileFilter);
}
public List getFileFilters() {
return Collections.unmodifiableList(this.fileFilters);
}
public boolean removeFileFilter(IOFileFilter ioFileFilter) {
return this.fileFilters.remove(ioFileFilter);
}
public void setFileFilters(List fileFilters) {
this.fileFilters = fileFilters;
}
public boolean accept(File file) {
for (Iterator iter = this.fileFilters.iterator(); iter.hasNext(); ) {
IOFileFilter fileFilter = (IOFileFilter)iter.next();
if (fileFilter.accept(file))
return true;
}
return false;
}
public boolean accept(File file, String name) {
for (Iterator iter = this.fileFilters.iterator(); iter.hasNext(); ) {
IOFileFilter fileFilter = (IOFileFilter)iter.next();
if (fileFilter.accept(file, name))
return true;
}
return false;
}
}

View file

@ -0,0 +1,43 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.util.List;
public class PrefixFileFilter extends AbstractFileFilter {
private String[] prefixes;
public PrefixFileFilter(String prefix) {
if (prefix == null)
throw new IllegalArgumentException("The prefix must not be null");
this.prefixes = new String[] { prefix };
}
public PrefixFileFilter(String[] prefixes) {
if (prefixes == null)
throw new IllegalArgumentException("The array of prefixes must not be null");
this.prefixes = prefixes;
}
public PrefixFileFilter(List prefixes) {
if (prefixes == null)
throw new IllegalArgumentException("The list of prefixes must not be null");
this.prefixes = (String[])prefixes.toArray(new String[prefixes.size()]);
}
public boolean accept(File file) {
String name = file.getName();
for (int i = 0; i < this.prefixes.length; i++) {
if (name.startsWith(this.prefixes[i]))
return true;
}
return false;
}
public boolean accept(File file, String name) {
for (int i = 0; i < this.prefixes.length; i++) {
if (name.startsWith(this.prefixes[i]))
return true;
}
return false;
}
}

View file

@ -0,0 +1,25 @@
package org.apache.commons.io.filefilter;
import java.io.File;
public class SizeFileFilter extends AbstractFileFilter {
private long size;
private boolean acceptLarger;
public SizeFileFilter(long size) {
this(size, true);
}
public SizeFileFilter(long size, boolean acceptLarger) {
if (size < 0L)
throw new IllegalArgumentException("The size must be non-negative");
this.size = size;
this.acceptLarger = acceptLarger;
}
public boolean accept(File file) {
boolean smaller = (file.length() < this.size);
return this.acceptLarger ? (!smaller) : smaller;
}
}

View file

@ -0,0 +1,43 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.util.List;
public class SuffixFileFilter extends AbstractFileFilter {
private String[] suffixes;
public SuffixFileFilter(String suffix) {
if (suffix == null)
throw new IllegalArgumentException("The suffix must not be null");
this.suffixes = new String[] { suffix };
}
public SuffixFileFilter(String[] suffixes) {
if (suffixes == null)
throw new IllegalArgumentException("The array of suffixes must not be null");
this.suffixes = suffixes;
}
public SuffixFileFilter(List suffixes) {
if (suffixes == null)
throw new IllegalArgumentException("The list of suffixes must not be null");
this.suffixes = (String[])suffixes.toArray(new String[suffixes.size()]);
}
public boolean accept(File file) {
String name = file.getName();
for (int i = 0; i < this.suffixes.length; i++) {
if (name.endsWith(this.suffixes[i]))
return true;
}
return false;
}
public boolean accept(File file, String name) {
for (int i = 0; i < this.suffixes.length; i++) {
if (name.endsWith(this.suffixes[i]))
return true;
}
return false;
}
}

View file

@ -0,0 +1,17 @@
package org.apache.commons.io.filefilter;
import java.io.File;
public class TrueFileFilter implements IOFileFilter {
public static final IOFileFilter TRUE = new TrueFileFilter();
public static final IOFileFilter INSTANCE = TRUE;
public boolean accept(File file) {
return true;
}
public boolean accept(File dir, String name) {
return true;
}
}

View file

@ -0,0 +1,62 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOCase;
public class WildcardFileFilter extends AbstractFileFilter {
private String[] wildcards;
private IOCase caseSensitivity;
public WildcardFileFilter(String wildcard) {
this(wildcard, 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;
}
public WildcardFileFilter(String[] wildcards) {
this(wildcards, 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;
}
public WildcardFileFilter(List wildcards) {
this(wildcards, null);
}
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;
}
public boolean accept(File dir, String name) {
for (int i = 0; i < this.wildcards.length; i++) {
if (FilenameUtils.wildcardMatch(name, this.wildcards[i], this.caseSensitivity))
return true;
}
return false;
}
public boolean accept(File file) {
String name = file.getName();
for (int i = 0; i < this.wildcards.length; i++) {
if (FilenameUtils.wildcardMatch(name, this.wildcards[i], this.caseSensitivity))
return true;
}
return false;
}
}

View file

@ -0,0 +1,47 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
public class WildcardFilter extends AbstractFileFilter {
private String[] wildcards;
public WildcardFilter(String wildcard) {
if (wildcard == null)
throw new IllegalArgumentException("The wildcard must not be null");
this.wildcards = new String[] { wildcard };
}
public WildcardFilter(String[] wildcards) {
if (wildcards == null)
throw new IllegalArgumentException("The wildcard array must not be null");
this.wildcards = wildcards;
}
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()]);
}
public boolean accept(File dir, String name) {
if (dir != null && new File(dir, name).isDirectory())
return false;
for (int i = 0; i < this.wildcards.length; i++) {
if (FilenameUtils.wildcardMatch(name, this.wildcards[i]))
return true;
}
return false;
}
public boolean accept(File file) {
if (file.isDirectory())
return false;
for (int i = 0; i < this.wildcards.length; i++) {
if (FilenameUtils.wildcardMatch(file.getName(), this.wildcards[i]))
return true;
}
return false;
}
}

View file

@ -0,0 +1,23 @@
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;
public class ClassLoaderObjectInputStream extends ObjectInputStream {
private ClassLoader classLoader;
public ClassLoaderObjectInputStream(ClassLoader classLoader, InputStream inputStream) throws IOException, StreamCorruptedException {
super(inputStream);
this.classLoader = classLoader;
}
protected Class resolveClass(ObjectStreamClass objectStreamClass) throws IOException, ClassNotFoundException {
Class clazz = Class.forName(objectStreamClass.getName(), false, this.classLoader);
if (clazz != null)
return clazz;
return super.resolveClass(objectStreamClass);
}
}

View file

@ -0,0 +1,60 @@
package org.apache.commons.io.input;
import java.io.IOException;
import java.io.InputStream;
public class CountingInputStream extends ProxyInputStream {
private long count;
public CountingInputStream(InputStream in) {
super(in);
}
public int read(byte[] b) throws IOException {
int found = super.read(b);
this.count += (found >= 0) ? (long)found : 0L;
return found;
}
public int read(byte[] b, int off, int len) throws IOException {
int found = super.read(b, off, len);
this.count += (found >= 0) ? (long)found : 0L;
return found;
}
public int read() throws IOException {
int found = super.read();
this.count += (found >= 0) ? 1L : 0L;
return found;
}
public long skip(long length) throws IOException {
long skip = super.skip(length);
this.count += skip;
return skip;
}
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;
}
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;
}
public synchronized long getByteCount() {
return this.count;
}
public synchronized long resetByteCount() {
long tmp = this.count;
this.count = 0L;
return tmp;
}
}

View file

@ -0,0 +1,31 @@
package org.apache.commons.io.input;
import java.io.IOException;
import java.io.InputStream;
public class DemuxInputStream extends InputStream {
private InheritableThreadLocal m_streams = new InheritableThreadLocal();
public InputStream bindStream(InputStream input) {
InputStream oldValue = getStream();
this.m_streams.set(input);
return oldValue;
}
public void close() throws IOException {
InputStream input = getStream();
if (null != input)
input.close();
}
public int read() throws IOException {
InputStream input = getStream();
if (null != input)
return input.read();
return -1;
}
private InputStream getStream() {
return (InputStream)this.m_streams.get();
}
}

View file

@ -0,0 +1,131 @@
package org.apache.commons.io.input;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
public class NullInputStream extends InputStream {
private long size;
private long position;
private long mark = -1L;
private long readlimit;
private boolean eof;
private boolean throwEofException;
private boolean markSupported;
public NullInputStream(long size) {
this(size, true, false);
}
public NullInputStream(long size, boolean markSupported, boolean throwEofException) {
this.size = size;
this.markSupported = markSupported;
this.throwEofException = throwEofException;
}
public long getPosition() {
return this.position;
}
public long getSize() {
return this.size;
}
public int available() {
long avail = this.size - this.position;
if (avail <= 0L)
return 0;
if (avail > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
return (int)avail;
}
public void close() throws IOException {
this.eof = false;
this.position = 0L;
this.mark = -1L;
}
public synchronized void mark(int readlimit) {
if (!this.markSupported)
throw new UnsupportedOperationException("Mark not supported");
this.mark = this.position;
this.readlimit = (long)readlimit;
}
public boolean markSupported() {
return this.markSupported;
}
public int read() throws IOException {
if (this.eof)
throw new IOException("Read after end of file");
if (this.position == this.size)
return doEndOfFile();
this.position++;
return processByte();
}
public int read(byte[] bytes) throws IOException {
return read(bytes, 0, bytes.length);
}
public int read(byte[] bytes, int offset, int length) throws IOException {
if (this.eof)
throw new IOException("Read after end of file");
if (this.position == this.size)
return doEndOfFile();
this.position += (long)length;
int returnLength = length;
if (this.position > this.size) {
returnLength = length - (int)(this.position - this.size);
this.position = this.size;
}
processBytes(bytes, offset, returnLength);
return returnLength;
}
public synchronized void reset() throws IOException {
if (!this.markSupported)
throw new UnsupportedOperationException("Mark not supported");
if (this.mark < 0L)
throw new IOException("No position has been marked");
if (this.position > this.mark + this.readlimit)
throw new IOException("Marked position [" + this.mark + "] is no longer valid - passed the read limit [" + this.readlimit + "]");
this.position = this.mark;
this.eof = false;
}
public long skip(long numberOfBytes) throws IOException {
if (this.eof)
throw new IOException("Skip after end of file");
if (this.position == this.size)
return (long)doEndOfFile();
this.position += numberOfBytes;
long returnLength = numberOfBytes;
if (this.position > this.size) {
returnLength = numberOfBytes - (this.position - this.size);
this.position = this.size;
}
return returnLength;
}
protected int processByte() {
return 0;
}
protected void processBytes(byte[] bytes, int offset, int length) {}
private int doEndOfFile() throws EOFException {
this.eof = true;
if (this.throwEofException)
throw new EOFException();
return -1;
}
}

View file

@ -0,0 +1,122 @@
package org.apache.commons.io.input;
import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;
public class NullReader extends Reader {
private long size;
private long position;
private long mark = -1L;
private long readlimit;
private boolean eof;
private boolean throwEofException;
private boolean markSupported;
public NullReader(long size) {
this(size, true, false);
}
public NullReader(long size, boolean markSupported, boolean throwEofException) {
this.size = size;
this.markSupported = markSupported;
this.throwEofException = throwEofException;
}
public long getPosition() {
return this.position;
}
public long getSize() {
return this.size;
}
public void close() throws IOException {
this.eof = false;
this.position = 0L;
this.mark = -1L;
}
public synchronized void mark(int readlimit) {
if (!this.markSupported)
throw new UnsupportedOperationException("Mark not supported");
this.mark = this.position;
this.readlimit = (long)readlimit;
}
public boolean markSupported() {
return this.markSupported;
}
public int read() throws IOException {
if (this.eof)
throw new IOException("Read after end of file");
if (this.position == this.size)
return doEndOfFile();
this.position++;
return processChar();
}
public int read(char[] chars) throws IOException {
return read(chars, 0, chars.length);
}
public int read(char[] chars, int offset, int length) throws IOException {
if (this.eof)
throw new IOException("Read after end of file");
if (this.position == this.size)
return doEndOfFile();
this.position += (long)length;
int returnLength = length;
if (this.position > this.size) {
returnLength = length - (int)(this.position - this.size);
this.position = this.size;
}
processChars(chars, offset, returnLength);
return returnLength;
}
public synchronized void reset() throws IOException {
if (!this.markSupported)
throw new UnsupportedOperationException("Mark not supported");
if (this.mark < 0L)
throw new IOException("No position has been marked");
if (this.position > this.mark + this.readlimit)
throw new IOException("Marked position [" + this.mark + "] is no longer valid - passed the read limit [" + this.readlimit + "]");
this.position = this.mark;
this.eof = false;
}
public long skip(long numberOfChars) throws IOException {
if (this.eof)
throw new IOException("Skip after end of file");
if (this.position == this.size)
return (long)doEndOfFile();
this.position += numberOfChars;
long returnLength = numberOfChars;
if (this.position > this.size) {
returnLength = numberOfChars - (this.position - this.size);
this.position = this.size;
}
return returnLength;
}
protected int processChar() {
return 0;
}
protected void processChars(char[] chars, int offset, int length) {}
private int doEndOfFile() throws EOFException {
this.eof = true;
if (this.throwEofException)
throw new EOFException();
return -1;
}
}

View file

@ -0,0 +1,47 @@
package org.apache.commons.io.input;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public abstract class ProxyInputStream extends FilterInputStream {
public ProxyInputStream(InputStream proxy) {
super(proxy);
}
public int read() throws IOException {
return this.in.read();
}
public int read(byte[] bts) throws IOException {
return this.in.read(bts);
}
public int read(byte[] bts, int st, int end) throws IOException {
return this.in.read(bts, st, end);
}
public long skip(long ln) throws IOException {
return this.in.skip(ln);
}
public int available() throws IOException {
return this.in.available();
}
public void close() throws IOException {
this.in.close();
}
public synchronized void mark(int idx) {
this.in.mark(idx);
}
public synchronized void reset() throws IOException {
this.in.reset();
}
public boolean markSupported() {
return this.in.markSupported();
}
}

View file

@ -0,0 +1,47 @@
package org.apache.commons.io.input;
import java.io.FilterReader;
import java.io.IOException;
import java.io.Reader;
public abstract class ProxyReader extends FilterReader {
public ProxyReader(Reader proxy) {
super(proxy);
}
public int read() throws IOException {
return this.in.read();
}
public int read(char[] chr) throws IOException {
return this.in.read(chr);
}
public int read(char[] chr, int st, int end) throws IOException {
return this.in.read(chr, st, end);
}
public long skip(long ln) throws IOException {
return this.in.skip(ln);
}
public boolean ready() throws IOException {
return this.in.ready();
}
public void close() throws IOException {
this.in.close();
}
public synchronized void mark(int idx) throws IOException {
this.in.mark(idx);
}
public synchronized void reset() throws IOException {
this.in.reset();
}
public boolean markSupported() {
return this.in.markSupported();
}
}

View file

@ -0,0 +1,80 @@
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;
public class SwappedDataInputStream extends ProxyInputStream implements DataInput {
public SwappedDataInputStream(InputStream input) {
super(input);
}
public boolean readBoolean() throws IOException, EOFException {
return (0 == readByte());
}
public byte readByte() throws IOException, EOFException {
return (byte)this.in.read();
}
public char readChar() throws IOException, EOFException {
return (char)readShort();
}
public double readDouble() throws IOException, EOFException {
return EndianUtils.readSwappedDouble(this.in);
}
public float readFloat() throws IOException, EOFException {
return EndianUtils.readSwappedFloat(this.in);
}
public void readFully(byte[] data) throws IOException, EOFException {
readFully(data, 0, data.length);
}
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;
}
}
public int readInt() throws IOException, EOFException {
return EndianUtils.readSwappedInteger(this.in);
}
public String readLine() throws IOException, EOFException {
throw new UnsupportedOperationException("Operation not supported: readLine()");
}
public long readLong() throws IOException, EOFException {
return EndianUtils.readSwappedLong(this.in);
}
public short readShort() throws IOException, EOFException {
return EndianUtils.readSwappedShort(this.in);
}
public int readUnsignedByte() throws IOException, EOFException {
return this.in.read();
}
public int readUnsignedShort() throws IOException, EOFException {
return EndianUtils.readSwappedUnsignedShort(this.in);
}
public String readUTF() throws IOException, EOFException {
throw new UnsupportedOperationException("Operation not supported: readUTF()");
}
public int skipBytes(int count) throws IOException, EOFException {
return (int)this.in.skip((long)count);
}
}

View file

@ -0,0 +1,138 @@
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class ByteArrayOutputStream extends OutputStream {
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
private List buffers = new ArrayList();
private int currentBufferIndex;
private int filledBufferSum;
private byte[] currentBuffer;
private int count;
public ByteArrayOutputStream() {
this(1024);
}
public ByteArrayOutputStream(int size) {
if (size < 0)
throw new IllegalArgumentException("Negative initial size: " + size);
needNewBuffer(size);
}
private byte[] getBuffer(int index) {
return (byte[])this.buffers.get(index);
}
private void needNewBuffer(int newcount) {
if (this.currentBufferIndex < this.buffers.size() - 1) {
this.filledBufferSum += this.currentBuffer.length;
this.currentBufferIndex++;
this.currentBuffer = getBuffer(this.currentBufferIndex);
} else {
int i;
if (this.currentBuffer == null) {
i = newcount;
this.filledBufferSum = 0;
} else {
i = Math.max(this.currentBuffer.length << 1, newcount - this.filledBufferSum);
this.filledBufferSum += this.currentBuffer.length;
}
this.currentBufferIndex++;
this.currentBuffer = new byte[i];
this.buffers.add(this.currentBuffer);
}
}
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();
if (len == 0)
return;
synchronized (this) {
int newcount = this.count + len;
int remaining = len;
int inBufferPos = this.count - this.filledBufferSum;
while (remaining > 0) {
int part = Math.min(remaining, this.currentBuffer.length - inBufferPos);
System.arraycopy(b, off + len - remaining, this.currentBuffer, inBufferPos, part);
remaining -= part;
if (remaining > 0) {
needNewBuffer(newcount);
inBufferPos = 0;
}
}
this.count = newcount;
}
}
public synchronized void write(int b) {
int inBufferPos = this.count - this.filledBufferSum;
if (inBufferPos == this.currentBuffer.length) {
needNewBuffer(this.count + 1);
inBufferPos = 0;
}
this.currentBuffer[inBufferPos] = (byte)b;
this.count++;
}
public synchronized int size() {
return this.count;
}
public void close() throws IOException {}
public synchronized void reset() {
this.count = 0;
this.filledBufferSum = 0;
this.currentBufferIndex = 0;
this.currentBuffer = getBuffer(this.currentBufferIndex);
}
public synchronized void writeTo(OutputStream out) throws IOException {
int remaining = this.count;
for (int i = 0; i < this.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;
}
}
public synchronized byte[] toByteArray() {
int remaining = this.count;
if (remaining == 0)
return EMPTY_BYTE_ARRAY;
byte[] newbuf = new byte[remaining];
int pos = 0;
for (int i = 0; i < this.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;
}
public String toString() {
return new String(toByteArray());
}
public String toString(String enc) throws UnsupportedEncodingException {
return new String(toByteArray(), enc);
}
}

View file

@ -0,0 +1,51 @@
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
public class CountingOutputStream extends ProxyOutputStream {
private long count;
public CountingOutputStream(OutputStream out) {
super(out);
}
public void write(byte[] b) throws IOException {
this.count += (long)b.length;
super.write(b);
}
public void write(byte[] b, int off, int len) throws IOException {
this.count += (long)len;
super.write(b, off, len);
}
public void write(int b) throws IOException {
this.count++;
super.write(b);
}
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;
}
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;
}
public synchronized long getByteCount() {
return this.count;
}
public synchronized long resetByteCount() {
long tmp = this.count;
this.count = 0L;
return tmp;
}
}

View file

@ -0,0 +1,70 @@
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;
public class DeferredFileOutputStream extends ThresholdingOutputStream {
private ByteArrayOutputStream memoryOutputStream;
private OutputStream currentOutputStream;
private File outputFile;
private boolean closed = false;
public DeferredFileOutputStream(int threshold, File outputFile) {
super(threshold);
this.outputFile = outputFile;
this.memoryOutputStream = new ByteArrayOutputStream();
this.currentOutputStream = this.memoryOutputStream;
}
protected OutputStream getStream() throws IOException {
return this.currentOutputStream;
}
protected void thresholdReached() throws IOException {
FileOutputStream fos = new FileOutputStream(this.outputFile);
this.memoryOutputStream.writeTo(fos);
this.currentOutputStream = fos;
this.memoryOutputStream = null;
}
public boolean isInMemory() {
return !isThresholdExceeded();
}
public byte[] getData() {
if (this.memoryOutputStream != null)
return this.memoryOutputStream.toByteArray();
return null;
}
public File getFile() {
return this.outputFile;
}
public void close() throws IOException {
super.close();
this.closed = true;
}
public void writeTo(OutputStream out) throws IOException {
if (!this.closed)
throw new IOException("Stream not closed");
if (isInMemory()) {
this.memoryOutputStream.writeTo(out);
} else {
FileInputStream fis = new FileInputStream(this.outputFile);
try {
IOUtils.copy(fis, out);
} finally {
IOUtils.closeQuietly(fis);
}
}
}
}

View file

@ -0,0 +1,36 @@
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
public class DemuxOutputStream extends OutputStream {
private InheritableThreadLocal m_streams = new InheritableThreadLocal();
public OutputStream bindStream(OutputStream output) {
OutputStream stream = getStream();
this.m_streams.set(output);
return stream;
}
public void close() throws IOException {
OutputStream output = getStream();
if (null != output)
output.close();
}
public void flush() throws IOException {
OutputStream output = getStream();
if (null != output)
output.flush();
}
public void write(int ch) throws IOException {
OutputStream output = getStream();
if (null != output)
output.write(ch);
}
private OutputStream getStream() {
return (OutputStream)this.m_streams.get();
}
}

View file

@ -0,0 +1,139 @@
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;
public class LockableFileWriter extends Writer {
private static final String LCK = ".lck";
private final Writer out;
private final File lockFile;
public LockableFileWriter(String fileName) throws IOException {
this(fileName, false, null);
}
public LockableFileWriter(String fileName, boolean append) throws IOException {
this(fileName, append, null);
}
public LockableFileWriter(String fileName, boolean append, String lockDir) throws IOException {
this(new File(fileName), append, lockDir);
}
public LockableFileWriter(File file) throws IOException {
this(file, false, null);
}
public LockableFileWriter(File file, boolean append) throws IOException {
this(file, append, null);
}
public LockableFileWriter(File file, boolean append, String lockDir) throws IOException {
this(file, null, append, lockDir);
}
public LockableFileWriter(File file, String encoding) throws IOException {
this(file, encoding, false, null);
}
public LockableFileWriter(File file, String encoding, boolean append, String lockDir) throws IOException {
file = file.getAbsoluteFile();
if (file.getParentFile() != null)
FileUtils.forceMkdir(file.getParentFile());
if (file.isDirectory())
throw new IOException("File specified is a directory");
if (lockDir == null)
lockDir = System.getProperty("java.io.tmpdir");
File lockDirFile = new File(lockDir);
FileUtils.forceMkdir(lockDirFile);
testLockDir(lockDirFile);
this.lockFile = new File(lockDirFile, file.getName() + ".lck");
createLock();
this.out = initWriter(file, encoding, append);
}
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());
}
private void createLock() throws IOException {
synchronized (LockableFileWriter.class) {
if (!this.lockFile.createNewFile())
throw new IOException("Can't write file, lock " + this.lockFile.getAbsolutePath() + " exists");
this.lockFile.deleteOnExit();
}
}
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);
this.lockFile.delete();
if (!fileExistedAlready)
file.delete();
throw ex;
} catch (RuntimeException ex) {
IOUtils.closeQuietly(writer);
IOUtils.closeQuietly(stream);
this.lockFile.delete();
if (!fileExistedAlready)
file.delete();
throw ex;
}
return writer;
}
public void close() throws IOException {
try {
this.out.close();
} finally {
this.lockFile.delete();
}
}
public void write(int idx) throws IOException {
this.out.write(idx);
}
public void write(char[] chr) throws IOException {
this.out.write(chr);
}
public void write(char[] chr, int st, int end) throws IOException {
this.out.write(chr, st, end);
}
public void write(String str) throws IOException {
this.out.write(str);
}
public void write(String str, int st, int end) throws IOException {
this.out.write(str, st, end);
}
public void flush() throws IOException {
this.out.flush();
}
}

View file

@ -0,0 +1,12 @@
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
public class NullOutputStream extends OutputStream {
public void write(byte[] b, int off, int len) {}
public void write(int b) {}
public void write(byte[] b) throws IOException {}
}

View file

@ -0,0 +1,19 @@
package org.apache.commons.io.output;
import java.io.Writer;
public class NullWriter extends Writer {
public void write(int idx) {}
public void write(char[] chr) {}
public void write(char[] chr, int st, int end) {}
public void write(String str) {}
public void write(String str, int st, int end) {}
public void flush() {}
public void close() {}
}

View file

@ -0,0 +1,31 @@
package org.apache.commons.io.output;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class ProxyOutputStream extends FilterOutputStream {
public ProxyOutputStream(OutputStream proxy) {
super(proxy);
}
public void write(int idx) throws IOException {
this.out.write(idx);
}
public void write(byte[] bts) throws IOException {
this.out.write(bts);
}
public void write(byte[] bts, int st, int end) throws IOException {
this.out.write(bts, st, end);
}
public void flush() throws IOException {
this.out.flush();
}
public void close() throws IOException {
this.out.close();
}
}

View file

@ -0,0 +1,39 @@
package org.apache.commons.io.output;
import java.io.FilterWriter;
import java.io.IOException;
import java.io.Writer;
public class ProxyWriter extends FilterWriter {
public ProxyWriter(Writer proxy) {
super(proxy);
}
public void write(int idx) throws IOException {
this.out.write(idx);
}
public void write(char[] chr) throws IOException {
this.out.write(chr);
}
public void write(char[] chr, int st, int end) throws IOException {
this.out.write(chr, st, end);
}
public void write(String str) throws IOException {
this.out.write(str);
}
public void write(String str, int st, int end) throws IOException {
this.out.write(str, st, end);
}
public void flush() throws IOException {
this.out.flush();
}
public void close() throws IOException {
this.out.close();
}
}

View file

@ -0,0 +1,38 @@
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
public class TeeOutputStream extends ProxyOutputStream {
protected OutputStream branch;
public TeeOutputStream(OutputStream out, OutputStream branch) {
super(out);
this.branch = branch;
}
public synchronized void write(byte[] b) throws IOException {
super.write(b);
this.branch.write(b);
}
public synchronized void write(byte[] b, int off, int len) throws IOException {
super.write(b, off, len);
this.branch.write(b, off, len);
}
public synchronized void write(int b) throws IOException {
super.write(b);
this.branch.write(b);
}
public void flush() throws IOException {
super.flush();
this.branch.flush();
}
public void close() throws IOException {
super.close();
this.branch.close();
}
}

View file

@ -0,0 +1,68 @@
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
public abstract class ThresholdingOutputStream extends OutputStream {
private int threshold;
private long written;
private boolean thresholdExceeded;
public ThresholdingOutputStream(int threshold) {
this.threshold = threshold;
}
public void write(int b) throws IOException {
checkThreshold(1);
getStream().write(b);
this.written++;
}
public void write(byte[] b) throws IOException {
checkThreshold(b.length);
getStream().write(b);
this.written += (long)b.length;
}
public void write(byte[] b, int off, int len) throws IOException {
checkThreshold(len);
getStream().write(b, off, len);
this.written += (long)len;
}
public void flush() throws IOException {
getStream().flush();
}
public void close() throws IOException {
try {
flush();
} catch (IOException ignored) {}
getStream().close();
}
public int getThreshold() {
return this.threshold;
}
public long getByteCount() {
return this.written;
}
public boolean isThresholdExceeded() {
return (this.written > (long)this.threshold);
}
protected void checkThreshold(int count) throws IOException {
if (!this.thresholdExceeded && this.written + (long)count > (long)this.threshold) {
thresholdReached();
this.thresholdExceeded = true;
}
}
protected abstract OutputStream getStream() throws IOException;
protected abstract void thresholdReached() throws IOException;
}