You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by je...@apache.org on 2003/08/21 20:40:48 UTC
cvs commit: jakarta-commons-sandbox/io/src/java/org/apache/commons/io CopyUtils.java FileUtils.java IOUtils.java
jeremias 2003/08/21 11:40:48
Modified: io/src/java/org/apache/commons/io FileUtils.java
IOUtils.java
Added: io/src/java/org/apache/commons/io CopyUtils.java
Log:
Bugzilla 22075: Copy copy methods from IOUtils to CopyUtils, deprecate old copy methods.
Bugzilla 22332: Deprecated FileUtils string methods, Code style-up
Submitted by: Matthew Hawthorne <mhawthorne at alumni.pitt.edu>
Revision Changes Path
1.14 +489 -484 jakarta-commons-sandbox/io/src/java/org/apache/commons/io/FileUtils.java
Index: FileUtils.java
===================================================================
RCS file: /home/cvs/jakarta-commons-sandbox/io/src/java/org/apache/commons/io/FileUtils.java,v
retrieving revision 1.13
retrieving revision 1.14
diff -u -r1.13 -r1.14
--- FileUtils.java 29 Jul 2003 13:07:39 -0000 1.13
+++ FileUtils.java 21 Aug 2003 18:40:48 -0000 1.14
@@ -55,10 +55,12 @@
import java.io.File;
import java.io.FileInputStream;
+import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;
+import java.util.Date;
import java.util.Vector;
/**
@@ -89,7 +91,7 @@
* </p>
*
* Common {@link java.io.File} manipulation routines.
- *
+ *
* <h3>Origin of code</h3>
* <ul>
* <li>commons-utils repo</li>
@@ -103,6 +105,7 @@
* @author <a href="mailto:Christoph.Reck@dlr.de">Christoph.Reck</a>
* @author <a href="mailto:peter@apache.org">Peter Donald</a>
* @author <a href="mailto:jefft@apache.org">Jeff Turner</a>
+ * @author Matthew Hawthorne
* @version $Id$
*/
public class FileUtils {
@@ -145,81 +148,7 @@
return displaySize;
}
- /**
- * Returns the directory path portion of a file specification string.
- * Matches the equally named unix command.
- * @param filename filename to inspect
- * @return The directory portion excluding the ending file separator.
- * @deprecated use getPath() instead.
- * TODO DELETE before 1.0
- */
- public static String dirname(String filename) {
- int i = filename.lastIndexOf(File.separator);
- return (i >= 0 ? filename.substring(0, i) : "");
- }
- /**
- * Returns the filename portion of a file specification string.
- * @param filename filename to inspect
- * @return The filename string with extension.
- * @deprecated use removeExtension() instead.
- * TODO DELETE before 1.0
- */
- public static String filename(String filename) {
- int i = filename.lastIndexOf(File.separator);
- return (i >= 0 ? filename.substring(i + 1) : filename);
- }
-
- /**
- * Returns the filename portion of a file specification string.
- * Matches the equally named unix command.
- * @param filename filename to inspect
- * @return The filename string without extension.
- * TODO DELETE before 1.0
- */
- public static String basename(String filename) {
- return basename(filename, extension(filename));
- }
-
- /**
- * Returns the filename portion of a file specification string.
- * Matches the equally named unix command.
- * @param filename filename to inspect
- * @param suffix additional remaining portion of name that if matches will
- * be removed
- * @return The filename string without the suffix.
- */
- public static String basename(String filename, String suffix) {
- int i = filename.lastIndexOf(File.separator) + 1;
- int lastDot = ((suffix != null) && (suffix.length() > 0))
- ? filename.lastIndexOf(suffix) : -1;
-
- if (lastDot >= 0) {
- return filename.substring(i, lastDot);
- } else if (i > 0) {
- return filename.substring(i);
- } else {
- return filename; // else returns all (no path and no extension)
- }
- }
-
- /**
- * Returns the extension portion of a file specification string.
- * This everything after the last dot '.' in the filename (NOT including
- * the dot).
- * @param filename filename to inspect
- * @return the extension
- * TODO probably duplicate method. See getExtension
- */
- public static String extension(String filename) {
- int lastDot = filename.lastIndexOf('.');
-
- if (lastDot >= 0) {
- return filename.substring(lastDot + 1);
- } else {
- return "";
- }
- }
/**
* Check if a file exits.
@@ -238,8 +167,8 @@
* @param fileName The name of the file to read.
* @return The file contents or null if read failed.
* @throws IOException in case of an I/O error
- * TODO This method should probably be removed or rethought.
- * Because it uses the default encoding only it should probably not be
+ * TODO This method should probably be removed or rethought.
+ * Because it uses the default encoding only it should probably not be
* used at all (platform-dependency)
*/
public static String fileRead(final String fileName) throws IOException {
@@ -257,11 +186,12 @@
* @param fileName The name of the file to write.
* @param data The content to write to the file.
* @throws IOException in case of an I/O error
- * TODO This method should probably be removed or rethought.
- * Because it uses the default encoding only it should probably not be
+ * TODO This method should probably be removed or rethought.
+ * Because it uses the default encoding only it should probably not be
* used at all (platform-dependency)
*/
- public static void fileWrite(String fileName, String data) throws IOException {
+ public static void fileWrite(String fileName, String data)
+ throws IOException {
FileOutputStream out = new FileOutputStream(fileName);
try {
out.write(data.getBytes());
@@ -269,23 +199,8 @@
IOUtils.shutdownStream(out);
}
}
-
- /**
- * Copy a file. The new file will be created if it does not exist. This is
- * an inefficient method, which just calls {@link #fileRead(String)} and
- * then {@link #fileWrite(String,String)}
- *
- * @param inFileName the file to copy
- * @param outFileName the file to copy to
- * @throws Exception if fileRead or fileWrite throw it
- * TODO This method is not a good idea. It doesn't do a binary copy. DELETE.
- */
- public static void fileCopy(String inFileName, String outFileName) throws
- Exception
- {
- String content = fileRead(inFileName);
- fileWrite(outFileName, content);
- }
+
+
/**
* Deletes a file.
@@ -318,8 +233,7 @@
}
try {
Thread.sleep(100);
- } catch (InterruptedException ignore) {
- } catch (Exception ex) {
+ } catch (InterruptedException ignore) {} catch (Exception ex) {
break;
}
}
@@ -346,7 +260,9 @@
*
* The given extensions should be like "java" and not like ".java"
*/
- public static String[] getFilesFromExtension(String directory, String[] extensions) {
+ public static String[] getFilesFromExtension(
+ String directory,
+ String[] extensions) {
Vector files = new Vector();
@@ -359,22 +275,24 @@
}
for (int i = 0; i < unknownFiles.length; ++i) {
- String currentFileName = directory + System.getProperty("file.separator") + unknownFiles[i];
+ String currentFileName =
+ directory
+ + System.getProperty("file.separator")
+ + unknownFiles[i];
java.io.File currentFile = new java.io.File(currentFileName);
if (currentFile.isDirectory()) {
-
//ignore all CVS directories...
if (currentFile.getName().equals("CVS")) {
continue;
}
-
//ok... transverse into this directory and get all the files... then combine
//them with the current list.
- String[] fetchFiles = getFilesFromExtension(currentFileName, extensions);
+ String[] fetchFiles =
+ getFilesFromExtension(currentFileName, extensions);
files = blendFilesToVector(files, fetchFiles);
} else {
@@ -398,7 +316,6 @@
}
-
/**
* Private hepler method for getFilesFromExtension()
*/
@@ -419,7 +336,6 @@
*/
private static boolean isValidFile(String file, String[] extensions) {
-
String extension = extension(file);
if (extension == null) {
extension = "";
@@ -449,7 +365,7 @@
}
}
-/* *** AVALON CODE *** */
+ /* *** AVALON CODE *** */
/**
* Compare the contents of two files to determine if they are equal or not.
@@ -459,40 +375,33 @@
* @return true if the content of the files are equal or they both don't exist, false otherwise
* @throws IOException in case of an I/O error
*/
- public static boolean contentEquals( final File file1, final File file2 )
- throws IOException
- {
+ public static boolean contentEquals(final File file1, final File file2)
+ throws IOException {
final boolean file1Exists = file1.exists();
- if( file1Exists != file2.exists() )
- {
+ if (file1Exists != file2.exists()) {
return false;
}
- if( !file1Exists )
- {
+ if (!file1Exists) {
// two not existing files are equal
return true;
}
- if( file1.isDirectory() || file2.isDirectory() )
- {
+ if (file1.isDirectory() || file2.isDirectory()) {
// don't want to compare directory contents
return false;
}
InputStream input1 = null;
InputStream input2 = null;
- try
- {
- input1 = new FileInputStream( file1 );
- input2 = new FileInputStream( file2 );
- return IOUtils.contentEquals( input1, input2 );
+ try {
+ input1 = new FileInputStream(file1);
+ input2 = new FileInputStream(file2);
+ return IOUtils.contentEquals(input1, input2);
- }
- finally
- {
- IOUtils.shutdownStream( input1 );
- IOUtils.shutdownStream( input2 );
+ } finally {
+ IOUtils.shutdownStream(input1);
+ IOUtils.shutdownStream(input2);
}
}
@@ -502,16 +411,13 @@
* @return The equivalent <code>File</code> object, or <code>null</code> if the URL's protocol
* is not <code>file</code>
*/
- public static File toFile( final URL url )
- {
- if( url.getProtocol().equals( "file" ) == false )
- {
+ public static File toFile(final URL url) {
+ if (url.getProtocol().equals("file") == false) {
return null;
- }
- else
- {
- final String filename = url.getFile().replace( '/', File.separatorChar );
- return new File( filename );
+ } else {
+ final String filename =
+ url.getFile().replace('/', File.separatorChar);
+ return new File(filename);
}
}
@@ -522,14 +428,11 @@
* @return the array of URLs
* @throws IOException if an error occurs
*/
- public static URL[] toURLs( final File[] files )
- throws IOException
- {
- final URL[] urls = new URL[ files.length ];
-
- for( int i = 0; i < urls.length; i++ )
- {
- urls[ i ] = files[ i ].toURL();
+ public static URL[] toURLs(final File[] files) throws IOException {
+ final URL[] urls = new URL[files.length];
+
+ for (int i = 0; i < urls.length; i++) {
+ urls[i] = files[i].toURL();
}
return urls;
@@ -547,17 +450,13 @@
* @param filename the filename
* @return the filename minus extension
*/
- public static String removeExtension( final String filename )
- {
- final int index = filename.lastIndexOf( '.' );
+ public static String removeExtension(final String filename) {
+ final int index = filename.lastIndexOf('.');
- if( -1 == index )
- {
+ if (-1 == index) {
return filename;
- }
- else
- {
- return filename.substring( 0, index );
+ } else {
+ return filename.substring(0, index);
}
}
@@ -573,17 +472,13 @@
* @param filename the filename
* @return the extension of filename or "" if none
*/
- public static String getExtension( final String filename )
- {
- final int index = filename.lastIndexOf( '.' );
+ public static String getExtension(final String filename) {
+ final int index = filename.lastIndexOf('.');
- if( -1 == index )
- {
+ if (-1 == index) {
return "";
- }
- else
- {
- return filename.substring( index + 1 );
+ } else {
+ return filename.substring(index + 1);
}
}
@@ -598,9 +493,8 @@
* @param filepath the filepath
* @return the filename minus path
*/
- public static String removePath( final String filepath )
- {
- return removePath( filepath, File.separatorChar );
+ public static String removePath(final String filepath) {
+ return removePath(filepath, File.separatorChar);
}
/**
@@ -615,17 +509,15 @@
* @param fileSeparatorChar the file separator character to use
* @return the filename minus path
*/
- public static String removePath( final String filepath, final char fileSeparatorChar )
- {
- final int index = filepath.lastIndexOf( fileSeparatorChar );
+ public static String removePath(
+ final String filepath,
+ final char fileSeparatorChar) {
+ final int index = filepath.lastIndexOf(fileSeparatorChar);
- if( -1 == index )
- {
+ if (-1 == index) {
return filepath;
- }
- else
- {
- return filepath.substring( index + 1 );
+ } else {
+ return filepath.substring(index + 1);
}
}
@@ -640,9 +532,8 @@
* @param filepath the filepath
* @return the filename minus path
*/
- public static String getPath( final String filepath )
- {
- return getPath( filepath, File.separatorChar );
+ public static String getPath(final String filepath) {
+ return getPath(filepath, File.separatorChar);
}
/**
@@ -657,39 +548,18 @@
* @param fileSeparatorChar the file separator character to use
* @return the filename minus path
*/
- public static String getPath( final String filepath, final char fileSeparatorChar )
- {
- final int index = filepath.lastIndexOf( fileSeparatorChar );
- if( -1 == index )
- {
+ public static String getPath(
+ final String filepath,
+ final char fileSeparatorChar) {
+ final int index = filepath.lastIndexOf(fileSeparatorChar);
+ if (-1 == index) {
return "";
- }
- else
- {
- return filepath.substring( 0, index );
+ } else {
+ return filepath.substring(0, index);
}
}
- /**
- * Copy file from source to destination. If <code>destinationDirectory</code> does not exist, it
- * (and any parent directories) will be created. If a file <code>source</code> in
- * <code>destinationDirectory</code> exists, it will be overwritten.
- *
- * @param source An existing <code>File</code> to copy.
- * @param destinationDirectory A directory to copy <code>source</code> into.
- *
- * @throws FileNotFoundException if <code>source</code> isn't a normal file.
- * @throws IllegalArgumentException if <code>destinationDirectory</code> isn't a directory.
- * @throws IOException if <code>source</code> does not exist, the file in
- * <code>destinationDirectory</code> cannot be written to, or an IO error occurs during copying.
- */
- public static void copyFileToDirectory( final String source,
- final String destinationDirectory )
- throws IOException
- {
- copyFileToDirectory( new File( source ),
- new File( destinationDirectory ) );
- }
+
/**
* Copy file from source to destination. If <code>destinationDirectory</code> does not exist, it
@@ -704,16 +574,16 @@
* @throws IOException if <code>source</code> does not exist, the file in
* <code>destinationDirectory</code> cannot be written to, or an IO error occurs during copying.
*/
- public static void copyFileToDirectory( final File source,
- final File destinationDirectory )
- throws IOException
- {
- if( destinationDirectory.exists() && !destinationDirectory.isDirectory() )
- {
- throw new IllegalArgumentException( "Destination is not a directory" );
+ public static void copyFileToDirectory(
+ final File source,
+ final File destinationDirectory)
+ throws IOException {
+ if (destinationDirectory.exists()
+ && !destinationDirectory.isDirectory()) {
+ throw new IllegalArgumentException("Destination is not a directory");
}
- copyFile( source, new File( destinationDirectory, source.getName() ) );
+ copyFile(source, new File(destinationDirectory, source.getName()));
}
/**
@@ -731,42 +601,46 @@
* @throws FileNotFoundException if <code>destination</code> is a directory
* (use {@link #copyFileToDirectory}).
*/
- public static void copyFile( final File source, final File destination )
- throws IOException
- {
+ public static void copyFile(final File source, final File destination)
+ throws IOException {
//check source exists
- if( !source.exists() )
- {
+ if (!source.exists()) {
final String message = "File " + source + " does not exist";
- throw new IOException( message );
+ throw new IOException(message);
}
//does destinations directory exist ?
- if( destination.getParentFile() != null &&
- !destination.getParentFile().exists() )
- {
+ if (destination.getParentFile() != null
+ && !destination.getParentFile().exists()) {
destination.getParentFile().mkdirs();
}
//make sure we can write to destination
- if( destination.exists() && !destination.canWrite() )
- {
- final String message = "Unable to open file " +
- destination + " for writing.";
- throw new IOException( message );
- }
-
- final FileInputStream input = new FileInputStream( source );
- final FileOutputStream output = new FileOutputStream( destination );
- IOUtils.copy( input, output );
- IOUtils.shutdownStream( input );
- IOUtils.shutdownStream( output );
-
- if( source.length() != destination.length() )
- {
- final String message = "Failed to copy full contents from " + source +
- " to " + destination;
- throw new IOException( message );
+ if (destination.exists() && !destination.canWrite()) {
+ final String message =
+ "Unable to open file " + destination + " for writing.";
+ throw new IOException(message);
+ }
+
+ final FileInputStream input = new FileInputStream(source);
+ try {
+ final FileOutputStream output = new FileOutputStream(destination);
+ try {
+ CopyUtils.copy(input, output);
+ } finally {
+ IOUtils.shutdownStream(output);
+ }
+ } finally {
+ IOUtils.shutdownStream(input);
+ }
+
+ if (source.length() != destination.length()) {
+ final String message =
+ "Failed to copy full contents from "
+ + source
+ + " to "
+ + destination;
+ throw new IOException(message);
}
}
@@ -786,29 +660,32 @@
* <li>an IO error occurs during copying</li>
* </ul>
*/
- public static void copyURLToFile( final URL source, final File destination )
- throws IOException
- {
+ public static void copyURLToFile(final URL source, final File destination)
+ throws IOException {
//does destination directory exist ?
- if( destination.getParentFile() != null &&
- !destination.getParentFile().exists() )
- {
+ if (destination.getParentFile() != null
+ && !destination.getParentFile().exists()) {
destination.getParentFile().mkdirs();
}
//make sure we can write to destination
- if( destination.exists() && !destination.canWrite() )
- {
- final String message = "Unable to open file " +
- destination + " for writing.";
- throw new IOException( message );
+ if (destination.exists() && !destination.canWrite()) {
+ final String message =
+ "Unable to open file " + destination + " for writing.";
+ throw new IOException(message);
}
final InputStream input = source.openStream();
- final FileOutputStream output = new FileOutputStream( destination );
- IOUtils.copy( input, output );
- IOUtils.shutdownStream( input );
- IOUtils.shutdownStream( output );
+ try {
+ final FileOutputStream output = new FileOutputStream(destination);
+ try {
+ CopyUtils.copy(input, output);
+ } finally {
+ IOUtils.shutdownStream(output);
+ }
+ } finally {
+ IOUtils.shutdownStream(input);
+ }
}
/**
@@ -829,40 +706,39 @@
* @param path the path to normalize
* @return the normalized String, or <code>null</code> if too many ..'s.
*/
- public static String normalize( final String path )
- {
+ public static String normalize(final String path) {
String normalized = path;
// Resolve occurrences of "//" in the normalized path
- while( true )
- {
- int index = normalized.indexOf( "//" );
- if( index < 0 )
+ while (true) {
+ int index = normalized.indexOf("//");
+ if (index < 0)
break;
- normalized = normalized.substring( 0, index ) +
- normalized.substring( index + 1 );
+ normalized =
+ normalized.substring(0, index)
+ + normalized.substring(index + 1);
}
// Resolve occurrences of "/./" in the normalized path
- while( true )
- {
- int index = normalized.indexOf( "/./" );
- if( index < 0 )
+ while (true) {
+ int index = normalized.indexOf("/./");
+ if (index < 0)
break;
- normalized = normalized.substring( 0, index ) +
- normalized.substring( index + 2 );
+ normalized =
+ normalized.substring(0, index)
+ + normalized.substring(index + 2);
}
// Resolve occurrences of "/../" in the normalized path
- while( true )
- {
- int index = normalized.indexOf( "/../" );
- if( index < 0 )
+ while (true) {
+ int index = normalized.indexOf("/../");
+ if (index < 0)
break;
- if( index == 0 )
- return null; // Trying to go outside our context
- int index2 = normalized.lastIndexOf( '/', index - 1 );
- normalized = normalized.substring( 0, index2 ) +
- normalized.substring( index + 3 );
+ if (index == 0)
+ return null; // Trying to go outside our context
+ int index2 = normalized.lastIndexOf('/', index - 1);
+ normalized =
+ normalized.substring(0, index2)
+ + normalized.substring(index + 3);
}
// Return the normalized path that we have completed
@@ -881,32 +757,27 @@
*
* @return The concatenated paths, or null if error occurs
*/
- public static String catPath( final String lookupPath, final String path )
- {
+ public static String catPath(final String lookupPath, final String path) {
// Cut off the last slash and everything beyond
- int index = lookupPath.lastIndexOf( "/" );
- String lookup = lookupPath.substring( 0, index );
+ int index = lookupPath.lastIndexOf("/");
+ String lookup = lookupPath.substring(0, index);
String pth = path;
// Deal with .. by chopping dirs off the lookup path
- while( pth.startsWith( "../" ) )
- {
- if( lookup.length() > 0 )
- {
- index = lookup.lastIndexOf( "/" );
- lookup = lookup.substring( 0, index );
- }
- else
- {
+ while (pth.startsWith("../")) {
+ if (lookup.length() > 0) {
+ index = lookup.lastIndexOf("/");
+ lookup = lookup.substring(0, index);
+ } else {
// More ..'s than dirs, return null
return null;
}
- index = pth.indexOf( "../" ) + 3;
- pth = pth.substring( index );
+ index = pth.indexOf("../") + 3;
+ pth = pth.substring(index);
}
- return new StringBuffer( lookup ).append( "/" ).append( pth ).toString();
+ return new StringBuffer(lookup).append("/").append(pth).toString();
}
/**
@@ -919,31 +790,23 @@
* @param filename Absolute or relative file path to resolve.
* @return The canonical <code>File</code> of <code>filename</code>.
*/
- public static File resolveFile( final File baseFile, String filename )
- {
+ public static File resolveFile(final File baseFile, String filename) {
String filenm = filename;
- if( '/' != File.separatorChar )
- {
- filenm = filename.replace( '/', File.separatorChar );
+ if ('/' != File.separatorChar) {
+ filenm = filename.replace('/', File.separatorChar);
}
- if( '\\' != File.separatorChar )
- {
- filenm = filename.replace( '\\', File.separatorChar );
+ if ('\\' != File.separatorChar) {
+ filenm = filename.replace('\\', File.separatorChar);
}
// deal with absolute files
- if( filenm.startsWith( File.separator ) )
- {
- File file = new File( filenm );
+ if (filenm.startsWith(File.separator)) {
+ File file = new File(filenm);
- try
- {
+ try {
file = file.getCanonicalFile();
- }
- catch( final IOException ioe )
- {
- }
+ } catch (final IOException ioe) {}
return file;
}
@@ -956,69 +819,51 @@
//on win32 at start of filename as UNC filenames can
//be \\AComputer\AShare\myfile.txt
int start = 0;
- if( '\\' == File.separatorChar )
- {
- sb.append( filenm.charAt( 0 ) );
+ if ('\\' == File.separatorChar) {
+ sb.append(filenm.charAt(0));
start++;
}
- for( int i = start; i < chars.length; i++ )
- {
+ for (int i = start; i < chars.length; i++) {
final boolean doubleSeparator =
- File.separatorChar == chars[ i ] && File.separatorChar == chars[ i - 1 ];
+ File.separatorChar == chars[i]
+ && File.separatorChar == chars[i - 1];
- if( !doubleSeparator )
- {
- sb.append( chars[ i ] );
+ if (!doubleSeparator) {
+ sb.append(chars[i]);
}
}
filenm = sb.toString();
//must be relative
- File file = ( new File( baseFile, filenm ) ).getAbsoluteFile();
+ File file = (new File(baseFile, filenm)).getAbsoluteFile();
- try
- {
+ try {
file = file.getCanonicalFile();
- }
- catch( final IOException ioe )
- {
- }
+ } catch (final IOException ioe) {}
return file;
}
- /**
- * Delete a file. If file is directory delete it and all sub-directories.
- * @param file file or directory to delete.
- * @throws IOException in case deletion is unsuccessful
- */
- public static void forceDelete( final String file )
- throws IOException
- {
- forceDelete( new File( file ) );
- }
+
/**
* Delete a file. If file is directory delete it and all sub-directories.
* @param file file or directory to delete.
* @throws IOException in case deletion is unsuccessful
*/
- public static void forceDelete( final File file )
- throws IOException
- {
- if( file.isDirectory() )
- {
- deleteDirectory( file );
- }
- else
- {
- if( !file.delete() )
- {
+ public static void forceDelete(final File file) throws IOException {
+ if (file.isDirectory()) {
+ deleteDirectory(file);
+ } else {
+ if (!file.exists()) {
+ throw new FileNotFoundException("File does not exist: " + file);
+ }
+ if (!file.delete()) {
final String message =
- "File " + file + " unable to be deleted.";
- throw new IOException( message );
+ "Unable to delete file: " + file;
+ throw new IOException(message);
}
}
}
@@ -1029,15 +874,10 @@
* @param file file or directory to delete.
* @throws IOException in case deletion is unsuccessful
*/
- public static void forceDeleteOnExit( final File file )
- throws IOException
- {
- if( file.isDirectory() )
- {
- deleteDirectoryOnExit( file );
- }
- else
- {
+ public static void forceDeleteOnExit(final File file) throws IOException {
+ if (file.isDirectory()) {
+ deleteDirectoryOnExit(file);
+ } else {
file.deleteOnExit();
}
}
@@ -1047,15 +887,13 @@
* @param directory directory to delete.
* @throws IOException in case deletion is unsuccessful
*/
- private static void deleteDirectoryOnExit( final File directory )
- throws IOException
- {
- if( !directory.exists() )
- {
+ private static void deleteDirectoryOnExit(final File directory)
+ throws IOException {
+ if (!directory.exists()) {
return;
}
- cleanDirectoryOnExit( directory );
+ cleanDirectoryOnExit(directory);
directory.deleteOnExit();
}
@@ -1064,68 +902,56 @@
* @param directory directory to clean.
* @throws IOException in case cleaning is unsuccessful
*/
- private static void cleanDirectoryOnExit( final File directory )
- throws IOException
- {
- if( !directory.exists() )
- {
+ private static void cleanDirectoryOnExit(final File directory)
+ throws IOException {
+ if (!directory.exists()) {
final String message = directory + " does not exist";
- throw new IllegalArgumentException( message );
+ throw new IllegalArgumentException(message);
}
- if( !directory.isDirectory() )
- {
+ if (!directory.isDirectory()) {
final String message = directory + " is not a directory";
- throw new IllegalArgumentException( message );
+ throw new IllegalArgumentException(message);
}
IOException exception = null;
final File[] files = directory.listFiles();
- for( int i = 0; i < files.length; i++ )
- {
- final File file = files[ i ];
- try
- {
- forceDeleteOnExit( file );
- }
- catch( final IOException ioe )
- {
+ for (int i = 0; i < files.length; i++) {
+ final File file = files[i];
+ try {
+ forceDeleteOnExit(file);
+ } catch (final IOException ioe) {
exception = ioe;
}
}
- if( null != exception )
- {
+ if (null != exception) {
throw exception;
}
}
-
/**
* Make a directory. If there already exists a file with specified name or
* the directory cannot be created then an exception is thrown.
* @param directory directory to create
* @throws IOException if the directory cannot be created.
*/
- public static void forceMkdir( final File directory )
- throws IOException
- {
- if( directory.exists() )
- {
- if( directory.isFile() )
- {
- final String message = "File " + directory + " exists and is " +
- "not a directory. Unable to create directory.";
- throw new IOException( message );
+ public static void forceMkdir(final File directory) throws IOException {
+ if (directory.exists()) {
+ if (directory.isFile()) {
+ final String message =
+ "File "
+ + directory
+ + " exists and is "
+ + "not a directory. Unable to create directory.";
+ throw new IOException(message);
}
- }
- else
- {
- if( false == directory.mkdirs() )
- {
- final String message = "Unable to create directory " + directory;
- throw new IOException( message );
+ } else {
+ if (false == directory.mkdirs()) {
+ final String message =
+ "Unable to create directory " + directory;
+ throw new IOException(message);
}
}
}
@@ -1135,31 +961,17 @@
* @param directory directory to delete
* @throws IOException in case deletion is unsuccessful
*/
- public static void deleteDirectory( final String directory )
- throws IOException
- {
- deleteDirectory( new File( directory ) );
- }
-
- /**
- * Recursively delete a directory.
- * @param directory directory to delete
- * @throws IOException in case deletion is unsuccessful
- */
- public static void deleteDirectory( final File directory )
- throws IOException
- {
- if( !directory.exists() )
- {
+ public static void deleteDirectory(final File directory)
+ throws IOException {
+ if (!directory.exists()) {
return;
}
- cleanDirectory( directory );
- if( !directory.delete() )
- {
+ cleanDirectory(directory);
+ if (!directory.delete()) {
final String message =
"Directory " + directory + " unable to be deleted.";
- throw new IOException( message );
+ throw new IOException(message);
}
}
@@ -1168,50 +980,31 @@
* @param directory directory to clean
* @throws IOException in case cleaning is unsuccessful
*/
- public static void cleanDirectory( final String directory )
- throws IOException
- {
- cleanDirectory( new File( directory ) );
- }
-
- /**
- * Clean a directory without deleting it.
- * @param directory directory to clean
- * @throws IOException in case cleaning is unsuccessful
- */
- public static void cleanDirectory( final File directory )
- throws IOException
- {
- if( !directory.exists() )
- {
+ public static void cleanDirectory(final File directory)
+ throws IOException {
+ if (!directory.exists()) {
final String message = directory + " does not exist";
- throw new IllegalArgumentException( message );
+ throw new IllegalArgumentException(message);
}
- if( !directory.isDirectory() )
- {
+ if (!directory.isDirectory()) {
final String message = directory + " is not a directory";
- throw new IllegalArgumentException( message );
+ throw new IllegalArgumentException(message);
}
IOException exception = null;
final File[] files = directory.listFiles();
- for( int i = 0; i < files.length; i++ )
- {
- final File file = files[ i ];
- try
- {
- forceDelete( file );
- }
- catch( final IOException ioe )
- {
+ for (int i = 0; i < files.length; i++) {
+ final File file = files[i];
+ try {
+ forceDelete(file);
+ } catch (final IOException ioe) {
exception = ioe;
}
}
- if( null != exception )
- {
+ if (null != exception) {
throw exception;
}
}
@@ -1222,49 +1015,261 @@
* @param directory directory to inspect
* @return size of directory in bytes.
*/
- public static long sizeOfDirectory( final String directory )
- {
- return sizeOfDirectory( new File( directory ) );
- }
-
- /**
- * Recursively count size of a directory (sum of the length of all files).
- *
- * @param directory directory to inspect
- * @return size of directory in bytes.
- */
- public static long sizeOfDirectory( final File directory )
- {
- if( !directory.exists() )
- {
+ public static long sizeOfDirectory(final File directory) {
+ if (!directory.exists()) {
final String message = directory + " does not exist";
- throw new IllegalArgumentException( message );
+ throw new IllegalArgumentException(message);
}
- if( !directory.isDirectory() )
- {
+ if (!directory.isDirectory()) {
final String message = directory + " is not a directory";
- throw new IllegalArgumentException( message );
+ throw new IllegalArgumentException(message);
}
long size = 0;
final File[] files = directory.listFiles();
- for( int i = 0; i < files.length; i++ )
- {
- final File file = files[ i ];
-
- if( file.isDirectory() )
- {
- size += sizeOfDirectory( file );
- }
- else
- {
+ for (int i = 0; i < files.length; i++) {
+ final File file = files[i];
+
+ if (file.isDirectory()) {
+ size += sizeOfDirectory(file);
+ } else {
size += file.length();
}
}
return size;
+ }
+
+ /**
+ * Tests if the specified <code>File</code> is newer than the reference
+ * <code>File</code>.
+ *
+ * @param file the <code>File</code> of which the modification date must be compared
+ * @param reference the <code>File</code> of which the modification date is used
+ * like reference
+ * @return true if the <code>File</code> exists and has been modified more recently
+ * than the reference <code>File</code>.
+ */
+ public static boolean isFileNewer(final File file, final File reference) {
+ if (reference == null) {
+ throw new IllegalArgumentException("No specified reference file");
+ }
+ if (!reference.exists()) {
+ throw new IllegalArgumentException("The reference file '" + file + "' doesn't exist");
+ }
+
+ return isFileNewer(file, reference.lastModified());
+ }
+
+ /**
+ * Tests if the specified <code>File</code> is newer than the specified
+ * <code>Date</code>
+ *
+ * @param file the <code>File</code> of which the modification date must be compared
+ * @param date the date reference
+ * @return true if the <code>File</code> exists and has been modified after
+ * the given <code>Date</code>.
+ */
+ public static boolean isFileNewer(final File file, final Date date) {
+ if (date == null) {
+ throw new IllegalArgumentException("No specified date");
+ }
+ return isFileNewer(file, date.getTime());
+ }
+
+ /**
+ * Tests if the specified <code>File</code> is newer than the specified
+ * time reference.
+ *
+ * @param file the <code>File</code> of which the modification date must be compared.
+ * @param timeMillis the time reference measured in milliseconds since the epoch
+ * (00:00:00 GMT, January 1, 1970)
+ * @return true if the <code>File</code> exists and has been modified after
+ * the given time reference.
+ */
+ public static boolean isFileNewer(final File file, final long timeMillis) {
+ if (file == null) {
+ throw new IllegalArgumentException("No specified file");
+ }
+ if (!file.exists()) {
+ return false;
+ }
+
+ return file.lastModified() > timeMillis;
+ }
+
+ // ----------------------------------------------------------------
+ // Deprecated methods
+ // ----------------------------------------------------------------
+
+ /**
+ * Returns the filename portion of a file specification string.
+ * Matches the equally named unix command.
+ * @param filename filename to inspect
+ * @return The filename string without extension.
+ * @deprecated This method will be deleted before a 1.0 release
+ * TODO DELETE before 1.0
+ */
+ public static String basename(String filename) {
+ return basename(filename, extension(filename));
+ }
+
+ /**
+ * Returns the filename portion of a file specification string.
+ * Matches the equally named unix command.
+ * @param filename filename to inspect
+ * @param suffix additional remaining portion of name that if matches will
+ * be removed
+ * @return The filename string without the suffix.
+ * @deprecated This method will be deleted.
+ */
+ public static String basename(String filename, String suffix) {
+ int i = filename.lastIndexOf(File.separator) + 1;
+ int lastDot =
+ ((suffix != null) && (suffix.length() > 0))
+ ? filename.lastIndexOf(suffix)
+ : -1;
+
+ if (lastDot >= 0) {
+ return filename.substring(i, lastDot);
+ } else if (i > 0) {
+ return filename.substring(i);
+ } else {
+ return filename; // else returns all (no path and no extension)
+ }
+ }
+
+ /**
+ * Delete a file. If file is directory delete it and all sub-directories.
+ * @param file file or directory to delete.
+ * @throws IOException in case deletion is unsuccessful
+ * @deprecated Use {@link #forceDelete(File)}
+ */
+ public static void forceDelete(final String file) throws IOException {
+ forceDelete(new File(file));
+ }
+
+
+
+ /**
+ * Clean a directory without deleting it.
+ * @param directory directory to clean
+ * @throws IOException in case cleaning is unsuccessful
+ * @deprecated Use {@link #cleanDirectory(File)}
+ */
+ public static void cleanDirectory(final String directory)
+ throws IOException {
+ cleanDirectory(new File(directory));
+ }
+
+ /**
+ * Recursively count size of a directory (sum of the length of all files).
+ *
+ * @param directory directory to inspect
+ * @return size of directory in bytes.
+ * @deprecated Use {@link #sizeOfDirectory(File)}
+ */
+ public static long sizeOfDirectory(final String directory) {
+ return sizeOfDirectory(new File(directory));
+ }
+
+ /**
+ * Copy file from source to destination. If <code>destinationDirectory</code> does not exist, it
+ * (and any parent directories) will be created. If a file <code>source</code> in
+ * <code>destinationDirectory</code> exists, it will be overwritten.
+ *
+ * @param source An existing <code>File</code> to copy.
+ * @param destinationDirectory A directory to copy <code>source</code> into.
+ *
+ * @throws FileNotFoundException if <code>source</code> isn't a normal file.
+ * @throws IllegalArgumentException if <code>destinationDirectory</code> isn't a directory.
+ * @throws IOException if <code>source</code> does not exist, the file in
+ * <code>destinationDirectory</code> cannot be written to, or an IO error occurs during copying.
+ *
+ * @deprecated Use {@link #copyFileToDirectory(File, File)}
+ */
+ public static void copyFileToDirectory(
+ final String source,
+ final String destinationDirectory)
+ throws IOException {
+ copyFileToDirectory(new File(source), new File(destinationDirectory));
+ }
+
+ /**
+ * Recursively delete a directory.
+ * @param directory directory to delete
+ * @throws IOException in case deletion is unsuccessful
+ * @deprecated Use {@link #deleteDirectory(File)}
+ */
+ public static void deleteDirectory(final String directory)
+ throws IOException {
+ deleteDirectory(new File(directory));
+ }
+
+ /**
+ * Returns the directory path portion of a file specification string.
+ * Matches the equally named unix command.
+ * @param filename filename to inspect
+ * @return The directory portion excluding the ending file separator.
+ * @deprecated Use {@link #getPath(File)}
+ * TODO DELETE before 1.0
+ */
+ public static String dirname(String filename) {
+ int i = filename.lastIndexOf(File.separator);
+ return (i >= 0 ? filename.substring(0, i) : "");
+ }
+
+ /**
+ * Returns the filename portion of a file specification string.
+ * @param filename filename to inspect
+ * @return The filename string with extension.
+ * @deprecated Use {@link #removeExtension(File)}
+ * TODO DELETE before 1.0
+ */
+ public static String filename(String filename) {
+ int i = filename.lastIndexOf(File.separator);
+ return (i >= 0 ? filename.substring(i + 1) : filename);
+ }
+
+
+
+ /**
+ * Returns the extension portion of a file specification string.
+ * This everything after the last dot '.' in the filename (NOT including
+ * the dot).
+ * @param filename filename to inspect
+ * @return the extension
+ * @deprecated Use {@link #getExtension(File)}
+ * TODO probably duplicate method. See getExtension
+ */
+ public static String extension(String filename) {
+ int lastDot = filename.lastIndexOf('.');
+
+ if (lastDot >= 0) {
+ return filename.substring(lastDot + 1);
+ } else {
+ return "";
+ }
+ }
+
+ /**
+ * Copy a file. The new file will be created if it does not exist. This is
+ * an inefficient method, which just calls {@link #fileRead(String)} and
+ * then {@link #fileWrite(String,String)}
+ *
+ * @param inFileName the file to copy
+ * @param outFileName the file to copy to
+ * @throws Exception if fileRead or fileWrite throw it
+ * @deprecated This method will be deleted.
+ *
+ * TODO This method is not a good idea. It doesn't do a binary copy. DELETE.
+ */
+ public static void fileCopy(String inFileName, String outFileName)
+ throws Exception {
+ String content = fileRead(inFileName);
+ fileWrite(outFileName, content);
}
}
1.5 +28 -4 jakarta-commons-sandbox/io/src/java/org/apache/commons/io/IOUtils.java
Index: IOUtils.java
===================================================================
RCS file: /home/cvs/jakarta-commons-sandbox/io/src/java/org/apache/commons/io/IOUtils.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- IOUtils.java 29 Jul 2003 13:07:39 -0000 1.4
+++ IOUtils.java 21 Aug 2003 18:40:48 -0000 1.5
@@ -135,9 +135,9 @@
* 14 copy byte[] OutputStream (trivial)
* </pre>
*
- * <p>Note that only the first two methods shuffle bytes; the rest use these
- * two, or (if possible) copy using native Java copy methods. As there are
- * method variants to specify buffer size and encoding, each row may
+ * <p>Note that only the first two methods shuffle bytes; the rest use these
+ * two, or (if possible) copy using native Java copy methods. As there are
+ * method variants to specify buffer size and encoding, each row may
* correspond to up to 4 methods.</p>
*
* <p>Origin of code: Apache Avalon (Excalibur)</p>
@@ -151,6 +151,11 @@
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
/**
+ * Instances should NOT be constructed in standard programming.
+ */
+ public IOUtils() {}
+
+ /**
* Unconditionally close an <code>Reader</code>.
* Equivalent to {@link Reader#close()}, except any exceptions will be ignored.
*
@@ -246,6 +251,7 @@
* @param output the <code>OutputStream</code> to write to
* @return the number of bytes copied
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(InputStream, OutputStream)}
*/
public static int copy( final InputStream input, final OutputStream output )
throws IOException
@@ -260,6 +266,7 @@
* @param bufferSize Size of internal buffer to use.
* @return the number of bytes copied
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(InputStream, OutputStream, int)}
*/
public static int copy( final InputStream input,
final OutputStream output,
@@ -283,6 +290,7 @@
* @param output the <code>Writer</code> to write to
* @return the number of characters copied
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(Reader, Writer)}
*/
public static int copy( final Reader input, final Writer output )
throws IOException
@@ -297,6 +305,7 @@
* @param bufferSize Size of internal buffer to use.
* @return the number of characters copied
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(Reader, Writer, int)}
*/
public static int copy( final Reader input, final Writer output, final int bufferSize )
throws IOException
@@ -328,6 +337,7 @@
* @param input the <code>InputStream</code> to read from
* @param output the <code>Writer</code> to write to
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(InputStream, Writer)}
*/
public static void copy( final InputStream input, final Writer output )
throws IOException
@@ -343,6 +353,7 @@
* @param output the <code>Writer</code> to write to
* @param bufferSize Size of internal buffer to use.
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(InputStream, Writer, int)}
*/
public static void copy( final InputStream input, final Writer output, final int bufferSize )
throws IOException
@@ -360,6 +371,7 @@
* <a href="http://www.iana.org/assignments/character-sets">IANA
* Charset Registry</a> for a list of valid encoding types.
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(InputStream, Writer, String)}
*/
public static void copy( final InputStream input, final Writer output, final String encoding )
throws IOException
@@ -378,6 +390,7 @@
* Charset Registry</a> for a list of valid encoding types.
* @param bufferSize Size of internal buffer to use.
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(InputStream, Writer, String, int)}
*/
public static void copy( final InputStream input,
final Writer output,
@@ -501,6 +514,7 @@
* @param input the <code>Reader</code> to read from
* @param output the <code>OutputStream</code> to write to
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(Reader, OutputStream)}
*/
public static void copy( final Reader input, final OutputStream output )
throws IOException
@@ -515,6 +529,7 @@
* @param output the <code>OutputStream</code> to write to
* @param bufferSize Size of internal buffer to use.
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(Reader, OutputStream, int)}
*/
public static void copy( final Reader input, final OutputStream output, final int bufferSize )
throws IOException
@@ -601,6 +616,7 @@
* @param input the <code>String</code> to read from
* @param output the <code>OutputStream</code> to write to
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(String, OutputStream)}
*/
public static void copy( final String input, final OutputStream output )
throws IOException
@@ -615,6 +631,7 @@
* @param output the <code>OutputStream</code> to write to
* @param bufferSize Size of internal buffer to use.
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(String, OutputStream, int)}
*/
public static void copy( final String input, final OutputStream output, final int bufferSize )
throws IOException
@@ -637,6 +654,7 @@
* @param input the <code>String</code> to read from
* @param output the <code>Writer</code> to write to
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(String, Writer)}
*/
public static void copy( final String input, final Writer output )
throws IOException
@@ -691,6 +709,7 @@
* @param input the byte array to read from
* @param output the <code>Writer</code> to write to
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(byte[], Writer)}
*/
public static void copy( final byte[] input, final Writer output )
throws IOException
@@ -706,6 +725,7 @@
* @param output the <code>Writer</code> to write to
* @param bufferSize Size of internal buffer to use.
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(byte[], Writer, int)}
*/
public static void copy( final byte[] input, final Writer output, final int bufferSize )
throws IOException
@@ -723,6 +743,7 @@
* <a href="http://www.iana.org/assignments/character-sets">IANA
* Charset Registry</a> for a list of valid encoding types.
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(byte[], Writer, String)}
*/
public static void copy( final byte[] input, final Writer output, final String encoding )
throws IOException
@@ -741,6 +762,7 @@
* Charset Registry</a> for a list of valid encoding types.
* @param bufferSize Size of internal buffer to use.
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(byte[], Writer, String, int)}
*/
public static void copy( final byte[] input,
final Writer output,
@@ -829,6 +851,7 @@
* @param input the byte array to read from
* @param output the <code>OutputStream</code> to write to
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(byte[], OutputStream)}
*/
public static void copy( final byte[] input, final OutputStream output )
throws IOException
@@ -842,6 +865,7 @@
* @param output the <code>OutputStream</code> to write to
* @param bufferSize Size of internal buffer to use.
* @throws IOException In case of an I/O problem
+ * @deprecated Replaced by {@link CopyUtils#copy(byte[], OutputStream, int)}
*/
public static void copy( final byte[] input,
final OutputStream output,
1.1 jakarta-commons-sandbox/io/src/java/org/apache/commons/io/CopyUtils.java
Index: CopyUtils.java
===================================================================
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
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;
/**
* Utility methods for copying data.
*
* @author Peter Donald
* @author Jeff Turner
* @author Matthew Hawthorne
* @version $Id: CopyUtils.java,v 1.1 2003/08/21 18:40:48 jeremias Exp $
*/
public class CopyUtils {
/**
* The name says it all.
*/
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
/**
* Instances should NOT be constructed in standard programming.
*/
public CopyUtils() {}
// ----------------------------------------------------------------
// byte[] -> OutputStream
// ----------------------------------------------------------------
/**
* Copy bytes from a <code>byte[]</code> to an <code>OutputStream</code>.
* @param input the byte array to read from
* @param output the <code>OutputStream</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(final byte[] input, final OutputStream output)
throws IOException {
copy(input, output, DEFAULT_BUFFER_SIZE);
}
/**
* Copy bytes from a <code>byte[]</code> to an <code>OutputStream</code>.
* @param input the byte array to read from
* @param output the <code>OutputStream</code> to write to
* @param bufferSize Size of internal buffer to use.
* @throws IOException In case of an I/O problem
*/
public static void copy(
final byte[] input,
final OutputStream output,
int bufferSize)
throws IOException {
// TODO Is bufferSize param needed?
output.write(input);
}
// ----------------------------------------------------------------
// byte[] -> Writer
// ----------------------------------------------------------------
/**
* Copy and convert bytes from a <code>byte[]</code> to chars on a
* <code>Writer</code>.
* The platform's default encoding is used for the byte-to-char conversion.
* @param input the byte array to read from
* @param output the <code>Writer</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(final byte[] input, final Writer output)
throws IOException {
copy(input, output, DEFAULT_BUFFER_SIZE);
}
/**
* Copy and convert bytes from a <code>byte[]</code> to chars on a
* <code>Writer</code>.
* The platform's default encoding is used for the byte-to-char conversion.
* @param input the byte array to read from
* @param output the <code>Writer</code> to write to
* @param bufferSize Size of internal buffer to use.
* @throws IOException In case of an I/O problem
*/
public static void copy(
final byte[] input,
final Writer output,
final int bufferSize)
throws IOException {
final ByteArrayInputStream in = new ByteArrayInputStream(input);
copy(in, output, bufferSize);
}
/**
* Copy and convert bytes from a <code>byte[]</code> to chars on a
* <code>Writer</code>, using the specified encoding.
* @param input the byte array to read from
* @param output the <code>Writer</code> to write to
* @param encoding The name of a supported character encoding. See the
* <a href="http://www.iana.org/assignments/character-sets">IANA
* Charset Registry</a> for a list of valid encoding types.
* @throws IOException In case of an I/O problem
*/
public static void copy(
final byte[] input,
final Writer output,
final String encoding)
throws IOException {
final ByteArrayInputStream in = new ByteArrayInputStream(input);
copy(in, output, encoding);
}
/**
* Copy and convert bytes from a <code>byte[]</code> to chars on a
* <code>Writer</code>, using the specified encoding.
* @param input the byte array to read from
* @param output the <code>Writer</code> to write to
* @param encoding The name of a supported character encoding. See the
* <a href="http://www.iana.org/assignments/character-sets">IANA
* Charset Registry</a> for a list of valid encoding types.
* @param bufferSize Size of internal buffer to use.
* @throws IOException In case of an I/O problem
*/
public static void copy(
final byte[] input,
final Writer output,
final String encoding,
final int bufferSize)
throws IOException {
final ByteArrayInputStream in = new ByteArrayInputStream(input);
copy(in, output, encoding, bufferSize);
}
// ----------------------------------------------------------------
// Core copy methods
// ----------------------------------------------------------------
/**
* Copy bytes from an <code>InputStream</code> to an <code>OutputStream</code>.
* @param input the <code>InputStream</code> to read from
* @param output the <code>OutputStream</code> to write to
* @return the number of bytes copied
* @throws IOException In case of an I/O problem
*/
public static int copy(final InputStream input, final OutputStream output)
throws IOException {
return copy(input, output, DEFAULT_BUFFER_SIZE);
}
/**
* Copy bytes from an <code>InputStream</code> to an <code>OutputStream</code>.
* @param input the <code>InputStream</code> to read from
* @param output the <code>OutputStream</code> to write to
* @param bufferSize Size of internal buffer to use.
* @return the number of bytes copied
* @throws IOException In case of an I/O problem
*/
public static int copy(
final InputStream input,
final OutputStream output,
final int bufferSize)
throws IOException {
final byte[] buffer = new byte[bufferSize];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
// ----------------------------------------------------------------
// Reader -> Writer
// ----------------------------------------------------------------
/**
* Copy chars from a <code>Reader</code> to a <code>Writer</code>.
* @param input the <code>Reader</code> to read from
* @param output the <code>Writer</code> to write to
* @return the number of characters copied
* @throws IOException In case of an I/O problem
*/
public static int copy(final Reader input, final Writer output)
throws IOException {
return copy(input, output, DEFAULT_BUFFER_SIZE);
}
/**
* Copy chars from a <code>Reader</code> to a <code>Writer</code>.
* @param input the <code>Reader</code> to read from
* @param output the <code>Writer</code> to write to
* @param bufferSize Size of internal buffer to use.
* @return the number of characters copied
* @throws IOException In case of an I/O problem
*/
public static int copy(
final Reader input,
final Writer output,
final int bufferSize)
throws IOException {
final char[] buffer = new char[bufferSize];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
// ----------------------------------------------------------------
// InputStream -> Writer
// ----------------------------------------------------------------
/**
* Copy and convert bytes from an <code>InputStream</code> to chars on a
* <code>Writer</code>.
* The platform's default encoding is used for the byte-to-char conversion.
* @param input the <code>InputStream</code> to read from
* @param output the <code>Writer</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(final InputStream input, final Writer output)
throws IOException {
copy(input, output, DEFAULT_BUFFER_SIZE);
}
/**
* Copy and convert bytes from an <code>InputStream</code> to chars on a
* <code>Writer</code>.
* The platform's default encoding is used for the byte-to-char conversion.
* @param input the <code>InputStream</code> to read from
* @param output the <code>Writer</code> to write to
* @param bufferSize Size of internal buffer to use.
* @throws IOException In case of an I/O problem
*/
public static void copy(
final InputStream input,
final Writer output,
final int bufferSize)
throws IOException {
final InputStreamReader in = new InputStreamReader(input);
copy(in, output, bufferSize);
}
/**
* Copy and convert bytes from an <code>InputStream</code> to chars on a
* <code>Writer</code>, using the specified encoding.
* @param input the <code>InputStream</code> to read from
* @param output the <code>Writer</code> to write to
* @param encoding The name of a supported character encoding. See the
* <a href="http://www.iana.org/assignments/character-sets">IANA
* Charset Registry</a> for a list of valid encoding types.
* @throws IOException In case of an I/O problem
*/
public static void copy(
final InputStream input,
final Writer output,
final String encoding)
throws IOException {
final InputStreamReader in = new InputStreamReader(input, encoding);
copy(in, output);
}
/**
* Copy and convert bytes from an <code>InputStream</code> to chars on a
* <code>Writer</code>, using the specified encoding.
* @param input the <code>InputStream</code> to read from
* @param output the <code>Writer</code> to write to
* @param encoding The name of a supported character encoding. See the
* <a href="http://www.iana.org/assignments/character-sets">IANA
* Charset Registry</a> for a list of valid encoding types.
* @param bufferSize Size of internal buffer to use.
* @throws IOException In case of an I/O problem
*/
public static void copy(
final InputStream input,
final Writer output,
final String encoding,
final int bufferSize)
throws IOException {
final InputStreamReader in = new InputStreamReader(input, encoding);
copy(in, output, bufferSize);
}
// ----------------------------------------------------------------
// Reader -> OutputStream
// ----------------------------------------------------------------
/**
* Serialize chars from a <code>Reader</code> to bytes on an
* <code>OutputStream</code>, and flush the <code>OutputStream</code>.
* @param input the <code>Reader</code> to read from
* @param output the <code>OutputStream</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(final Reader input, final OutputStream output)
throws IOException {
copy(input, output, DEFAULT_BUFFER_SIZE);
}
/**
* Serialize chars from a <code>Reader</code> to bytes on an
* <code>OutputStream</code>, and flush the <code>OutputStream</code>.
* @param input the <code>Reader</code> to read from
* @param output the <code>OutputStream</code> to write to
* @param bufferSize Size of internal buffer to use.
* @throws IOException In case of an I/O problem
*/
public static void copy(
final Reader input,
final OutputStream output,
final int bufferSize)
throws IOException {
final OutputStreamWriter out = new OutputStreamWriter(output);
copy(input, out, bufferSize);
// XXX Unless anyone is planning on rewriting OutputStreamWriter, we have to flush here.
out.flush();
}
// ----------------------------------------------------------------
// String -> OutputStream
// ----------------------------------------------------------------
/**
* Serialize chars from a <code>String</code> to bytes on an <code>OutputStream</code>, and
* flush the <code>OutputStream</code>.
* @param input the <code>String</code> to read from
* @param output the <code>OutputStream</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(final String input, final OutputStream output)
throws IOException {
copy(input, output, DEFAULT_BUFFER_SIZE);
}
/**
* Serialize chars from a <code>String</code> to bytes on an <code>OutputStream</code>, and
* flush the <code>OutputStream</code>.
* @param input the <code>String</code> to read from
* @param output the <code>OutputStream</code> to write to
* @param bufferSize Size of internal buffer to use.
* @throws IOException In case of an I/O problem
*/
public static void copy(
final String input,
final OutputStream output,
final int bufferSize)
throws IOException {
final StringReader in = new StringReader(input);
final OutputStreamWriter out = new OutputStreamWriter(output);
copy(in, out, bufferSize);
// XXX Unless anyone is planning on rewriting OutputStreamWriter, we have to flush here.
out.flush();
}
// ----------------------------------------------------------------
// String -> Writer
// ----------------------------------------------------------------
/**
* Copy chars from a <code>String</code> to a <code>Writer</code>.
* @param input the <code>String</code> to read from
* @param output the <code>Writer</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(final String input, final Writer output)
throws IOException {
output.write(input);
}
} // CopyUtils
Re: cvs commit: jakarta-commons-sandbox/io/src/java/org/apache/commons/io FileUtils.java
Posted by Jeremias Maerki <de...@greenmail.ch>.
I forgot to credit Alban Peignier <alban.peignier at free.fr> for his
isFileNewer methods. I'm sorry. I shouldn't do more than a couple of
things at once.
http://nagoya.apache.org/eyebrowse/BrowseList?listName=commons-dev@jakarta.apache.org&by=thread&from=348688
On 21.08.2003 20:40:48 jeremias wrote:
> jeremias 2003/08/21 11:40:48
>
> Modified: io/src/java/org/apache/commons/io FileUtils.java
<snip/>
> Index: FileUtils.java
> ===================================================================
> RCS file: /home/cvs/jakarta-commons-sandbox/io/src/java/org/apache/commons/io/FileUtils.java,v
> retrieving revision 1.13
> retrieving revision 1.14
> diff -u -r1.13 -r1.14
<snip/>
> + /**
> + * Tests if the specified <code>File</code> is newer than the reference
> + * <code>File</code>.
> + *
> + * @param file the <code>File</code> of which the modification date must be compared
> + * @param reference the <code>File</code> of which the modification date is used
> + * like reference
> + * @return true if the <code>File</code> exists and has been modified more recently
> + * than the reference <code>File</code>.
> + */
> + public static boolean isFileNewer(final File file, final File reference) {
> + if (reference == null) {
> + throw new IllegalArgumentException("No specified reference file");
> + }
> + if (!reference.exists()) {
> + throw new IllegalArgumentException("The reference file '" + file + "' doesn't exist");
> + }
> +
> + return isFileNewer(file, reference.lastModified());
> + }
> +
> + /**
> + * Tests if the specified <code>File</code> is newer than the specified
> + * <code>Date</code>
> + *
> + * @param file the <code>File</code> of which the modification date must be compared
> + * @param date the date reference
> + * @return true if the <code>File</code> exists and has been modified after
> + * the given <code>Date</code>.
> + */
> + public static boolean isFileNewer(final File file, final Date date) {
> + if (date == null) {
> + throw new IllegalArgumentException("No specified date");
> + }
> + return isFileNewer(file, date.getTime());
> + }
> +
> + /**
> + * Tests if the specified <code>File</code> is newer than the specified
> + * time reference.
> + *
> + * @param file the <code>File</code> of which the modification date must be compared.
> + * @param timeMillis the time reference measured in milliseconds since the epoch
> + * (00:00:00 GMT, January 1, 1970)
> + * @return true if the <code>File</code> exists and has been modified after
> + * the given time reference.
> + */
> + public static boolean isFileNewer(final File file, final long timeMillis) {
> + if (file == null) {
> + throw new IllegalArgumentException("No specified file");
> + }
> + if (!file.exists()) {
> + return false;
> + }
> +
> + return file.lastModified() > timeMillis;
> + }
Jeremias Maerki