edu.rice.cs.util
Class FileOps

java.lang.Object
  extended by edu.rice.cs.util.FileOps

public abstract class FileOps
extends Object

A class to provide some convenient file operations as static methods. It's abstract to prevent (useless) instantiation, though it can be subclassed to provide convenient namespace importation of its methods.

Version:
$Id: FileOps.java 4691 2008-12-02 23:33:27Z dlsmith $

Nested Class Summary
static class FileOps.DefaultFileSaver
          This class is a default implementation of FileSaver that makes only one backup of each file per instantiation of the program (following the Emacs convention).
static interface FileOps.FileSaver
           
static class FileOps.NullFile
          A singleton null file class.
 
Field Summary
static FileFilter JAVA_FILE_FILTER
          Deprecated. Use IOUtil.extensionFilePredicate(java.lang.String) instead. Example: IOUtil.extensionFileFilter("java").
static File NULL_FILE
          Special sentinal file used in FileOption and test classes among others.
 
Constructor Summary
FileOps()
           
 
Method Summary
static String convertToAbsolutePathEntries(String path)
          Deprecated. Use IOUtil.parsePath(java.lang.String), IOUtil.getAbsoluteFiles(java.lang.Iterable), IOUtil.attemptAbsoluteFiles(java.lang.Iterable), and IOUtil.pathToString(java.lang.Iterable), as needed, instead.
static void copyFile(File source, File dest)
          Deprecated. Use IOUtil.copyFile(java.io.File, java.io.File) instead; it scales in a much more efficiently.
static File createTempDirectory(String name)
          Create a new temporary directory.
static File createTempDirectory(String name, File parent)
          Create a new temporary directory.
static boolean deleteDirectory(File dir)
          Deprecated. Use IOUtil.deleteRecursively(java.io.File) instead
static void deleteDirectoryOnExit(File dir)
          Deprecated. Use IOUtil.deleteOnExitRecursively(java.io.File) instead
static File getCanonicalFile(File f)
          Deprecated. Use IOUtil.attemptCanonicalFile(java.io.File) instead.
static String getCanonicalPath(File f)
          Deprecated. Use IOUtil.attemptCanonicalFile(java.io.File) instead. (The result will be a File instead of a String.)
static ArrayList<File> getFilesInDir(File d, boolean recur, FileFilter f)
          Deprecated. Use IOUtil.attemptListFilesAsIterable(java.io.File) or IOUtil.listFilesRecursively(File, FileFilter, FileFilter) instead.
static File getValidDirectory(File origFile)
          Return a valid directory for use, i.e.
static boolean inFileTree(File f, File root)
          Deprecated. Use IOUtil.isMember(java.io.File, java.io.File) instead. Note that the new method does not test for null values and does not convert to canonical paths -- if these things are necessary, they should be done before invoking the method.
static boolean isAncestorOf(File ancestor, File f)
          Return true if the directory ancestor is an ancestor of the file f, i.e.
static File makeFile(File parentDir, String child)
          Deprecated. For a best-attempt canonical file, use IOUtil.attemptCanonicalFile(java.io.File) instead. (for example, IOUtil.attemptCanonicalFile(new File(path)))
static File makeFile(String path)
          Deprecated. For a best-attempt canonical file, use IOUtil.attemptCanonicalFile(java.io.File) instead. (for example, IOUtil.attemptCanonicalFile(new File(path)))
static File makeRelativeTo(File f, File b)
          Makes a file equivalent to the given file f that is relative to base file b.
static boolean makeWritable(File roFile)
           
static boolean moveRecursively(File f, File n)
          Move f to n, recursively if necessary.
static LinkedList<String> packageExplore(String prefix, File root)
          This function starts from the given directory and finds all packages within that directory
static String readFileAsString(File file)
          Deprecated. Use IOUtil.toString(File) instead, which provides the same functionality.
static String readFileAsSwingText(File file)
          Reads the entire contents of a file and return them as canonicalized Swing Document text.
static byte[] readStreamAsBytes(InputStream stream)
          Deprecated. Use IOUtil.toByteArray(java.io.File) instead. Note that the IOUtil method will not close the InputStream, while this method does.
static boolean renameFile(File file, File dest)
          Deprecated. Use IOUtil.attemptMove(java.io.File, java.io.File), which is equally Windows-friendly, instead.
static void saveFile(FileOps.FileSaver fileSaver)
          This method writes files correctly; it takes care of catching errors, making backups, and keeping an unsuccessful file save from destroying the old file (unless a backup is made).
static String[] splitFile(File fileToSplit)
          Deprecated. Use IOUtil.fullPath(java.io.File) instead. It returns a list of File objects rather than strings, but they appear in the same order.
static String stringMakeRelativeTo(File f, File b)
          Makes a file equivalent to the given file f that is relative to base file b.
static URL toURL(File f)
          Converts the abstract pathname for f into a URL.
static File validate(File f)
           
static boolean writeIfPossible(File file, String text, boolean append)
          Deprecated. Use IOUtil.attemptWriteStringToFile(File, String, boolean) instead.
static void writeStringToFile(File file, String text)
          Deprecated. Use the equivalent IOUtil.writeStringToFile(File, String) instead
static void writeStringToFile(File file, String text, boolean append)
          Deprecated. Use the equivalent IOUtil.writeStringToFile(File, String, boolean) instead
static File writeStringToNewTempFile(String prefix, String suffix, String text)
          Deprecated. Instead, create a temp file with IOUtil.createAndMarkTempFile(String, String), then write to it with IOUtil.writeStringToFile(File, String).
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

NULL_FILE

public static final File NULL_FILE
Special sentinal file used in FileOption and test classes among others.


JAVA_FILE_FILTER

@Deprecated
public static final FileFilter JAVA_FILE_FILTER
Deprecated. Use IOUtil.extensionFilePredicate(java.lang.String) instead. Example: IOUtil.extensionFileFilter("java").
This filter checks for files with names that end in ".java". (Note that while this filter was intended to be a javax.swing.filechooser.FileFilter, it actually implements a java.io.FileFilter, because that is what FileFilter means in the context of this source file.)

Constructor Detail

FileOps

public FileOps()
Method Detail

makeFile

@Deprecated
public static File makeFile(String path)
Deprecated. For a best-attempt canonical file, use IOUtil.attemptCanonicalFile(java.io.File) instead. (for example, IOUtil.attemptCanonicalFile(new File(path)))


makeFile

@Deprecated
public static File makeFile(File parentDir,
                                       String child)
Deprecated. For a best-attempt canonical file, use IOUtil.attemptCanonicalFile(java.io.File) instead. (for example, IOUtil.attemptCanonicalFile(new File(path)))


inFileTree

@Deprecated
public static boolean inFileTree(File f,
                                            File root)
Deprecated. Use IOUtil.isMember(java.io.File, java.io.File) instead. Note that the new method does not test for null values and does not convert to canonical paths -- if these things are necessary, they should be done before invoking the method.

Determines whether the specified file in within the specified file tree.


isAncestorOf

public static boolean isAncestorOf(File ancestor,
                                   File f)
Return true if the directory ancestor is an ancestor of the file f, i.e. you can get from f to ancestor by using getParentFile zero or more times.

Parameters:
ancestor - the ancestor
f - the file to test
Returns:
true if ancestor is an ancestor of f.

makeRelativeTo

public static File makeRelativeTo(File f,
                                  File b)
                           throws IOException,
                                  SecurityException
Makes a file equivalent to the given file f that is relative to base file b. In other words, new File(b,makeRelativeTo(base,abs)).getCanonicalPath() equals f.getCanonicalPath()

In Linux/Unix, if the file f is /home/username/folder/file.java and the file b is /home/username/folder/sublevel/file2.java, then the resulting File path from this method would be ../file.java while its canoncial path would be /home/username/folder/file.java.

Warning: making paths relative is inherently broken on some file systems, because a relative path requires that both the file and the base have the same root. The Windows file system, and therefore also the Java file system model, however, support multiple system roots (see File.listRoots()). Thus, two files with different roots cannot have a relative path. In that case the absolute path of the file will be returned

Parameters:
f - The path that is to be made relative to the base file
b - The file to make the next file relative to
Returns:
A new file whose path is relative to the base file while the value of getCanonicalPath() for the returned file is the same as the result of getCanonicalPath() for the given file.
Throws:
IOException
SecurityException

stringMakeRelativeTo

public static String stringMakeRelativeTo(File f,
                                          File b)
                                   throws IOException,
                                          SecurityException
Makes a file equivalent to the given file f that is relative to base file b. In other words, new File(b,makeRelativeTo(base,abs)).getCanonicalPath() equals f.getCanonicalPath()

In Linux/Unix, if the file f is /home/username/folder/file.java and the file b is /home/username/folder/sublevel/file2.java, then the resulting File path from this method would be ../file.java while its canoncial path would be /home/username/folder/file.java.

Warning: making paths relative is inherently broken on some file systems, because a relative path requires that both the file and the base have the same root. The Windows file system, and therefore also the Java file system model, however, support multiple system roots (see File.listRoots()). Thus, two files with different roots cannot have a relative path. In that case the absolute path of the file will be returned

Parameters:
f - The path that is to be made relative to the base file
b - The file to make the next file relative to
Returns:
A new file whose path is relative to the base file while the value of getCanonicalPath() for the returned file is the same as the result of getCanonicalPath() for the given file.
Throws:
IOException
SecurityException

splitFile

@Deprecated
public static String[] splitFile(File fileToSplit)
Deprecated. Use IOUtil.fullPath(java.io.File) instead. It returns a list of File objects rather than strings, but they appear in the same order.

Splits a file into an array of strings representing each parent folder of the given file. The file whose path is /home/username/txt.txt in linux would be split into the string array: {"","home","username","txt.txt"}. Delimeters are excluded.

Parameters:
fileToSplit - the file to split into its directories.

getFilesInDir

@Deprecated
public static ArrayList<File> getFilesInDir(File d,
                                                       boolean recur,
                                                       FileFilter f)
Deprecated. Use IOUtil.attemptListFilesAsIterable(java.io.File) or IOUtil.listFilesRecursively(File, FileFilter, FileFilter) instead.

List all files (that is, Files for which isFile() is true) matching the provided filter in the given directory.

Parameters:
d - The directory to search.
recur - Whether subdirectories accepted by f should be recursively searched. Note that subdirectories that aren't accepted by f will be ignored.
f - The filter to apply to contained Files.
Returns:
An array of Files in the directory specified; if the directory does not exist, returns an empty list.

getCanonicalFile

@Deprecated
public static File getCanonicalFile(File f)
Deprecated. Use IOUtil.attemptCanonicalFile(java.io.File) instead.

Returns:
the canonical file equivalent to f. Identical to f.getCanonicalFile() except it does not throw an exception when the file path syntax is incorrect (or an IOException or SecurityException occurs for any other reason). It returns the absolute File intead.

getCanonicalPath

@Deprecated
public static String getCanonicalPath(File f)
Deprecated. Use IOUtil.attemptCanonicalFile(java.io.File) instead. (The result will be a File instead of a String.)

Returns:
the canonical path for f. Identical to f.getCanonicalPath() except it does not throw an exception when the file path syntax is incorrect; it returns the absolute path instead.

validate

public static File validate(File f)
Returns:
the file f unchanged if f exists; otherwise returns NULL_FILE.

readStreamAsBytes

@Deprecated
public static byte[] readStreamAsBytes(InputStream stream)
                                throws IOException
Deprecated. Use IOUtil.toByteArray(java.io.File) instead. Note that the IOUtil method will not close the InputStream, while this method does.

Reads the stream until it reaches EOF, and then returns the read contents as a byte array. This call may block, since it will not return until EOF has been reached.

Parameters:
stream - Input stream to read.
Returns:
Byte array consisting of all data read from stream.
Throws:
IOException

readFileAsSwingText

public static String readFileAsSwingText(File file)
                                  throws IOException
Reads the entire contents of a file and return them as canonicalized Swing Document text. All newLine sequences, including "\n", "\r", and "\r\n" are converted to "\n".

Throws:
IOException

readFileAsString

@Deprecated
public static String readFileAsString(File file)
                               throws IOException
Deprecated. Use IOUtil.toString(File) instead, which provides the same functionality.

Reads the entire contents of a file and return them as a String.

Throws:
IOException

copyFile

@Deprecated
public static void copyFile(File source,
                                       File dest)
                     throws IOException
Deprecated. Use IOUtil.copyFile(java.io.File, java.io.File) instead; it scales in a much more efficiently.

Copies the text of one file into another.

Parameters:
source - the file to be copied
dest - the file to be copied to
Throws:
IOException

writeStringToNewTempFile

@Deprecated
public static File writeStringToNewTempFile(String prefix,
                                                       String suffix,
                                                       String text)
                                     throws IOException
Deprecated. Instead, create a temp file with IOUtil.createAndMarkTempFile(String, String), then write to it with IOUtil.writeStringToFile(File, String).

Creates a new temporary file and writes the given text to it. The file will be deleted on exit.

Parameters:
prefix - Beginning part of file name, before unique number
suffix - Ending part of file name, after unique number
text - Text to write to file
Returns:
name of the temporary file that was created
Throws:
IOException

writeStringToFile

@Deprecated
public static void writeStringToFile(File file,
                                                String text)
                              throws IOException
Deprecated. Use the equivalent IOUtil.writeStringToFile(File, String) instead

Writes text to the file overwriting whatever was there.

Parameters:
file - File to write to
text - Test to write
Throws:
IOException

writeStringToFile

@Deprecated
public static void writeStringToFile(File file,
                                                String text,
                                                boolean append)
                              throws IOException
Deprecated. Use the equivalent IOUtil.writeStringToFile(File, String, boolean) instead

Writes text to the file.

Parameters:
file - File to write to
text - Text to write
append - whether to append. (false=overwrite)
Throws:
IOException

writeIfPossible

@Deprecated
public static boolean writeIfPossible(File file,
                                                 String text,
                                                 boolean append)
Deprecated. Use IOUtil.attemptWriteStringToFile(File, String, boolean) instead.

Writes text to the given file returning true if it succeeded and false if not. This is a simple wrapper for writeStringToFile that doesn't throw an IOException.

Parameters:
file - File to write to
text - Text to write
append - Whether to append. (false=overwrite)

createTempDirectory

public static File createTempDirectory(String name)
                                throws IOException
Create a new temporary directory. The directory will be deleted on exit, if empty. (To delete it recursively on exit, use deleteDirectoryOnExit.)

Parameters:
name - Non-unique portion of the name of the directory to create.
Returns:
File representing the directory that was created.
Throws:
IOException

createTempDirectory

public static File createTempDirectory(String name,
                                       File parent)
                                throws IOException
Create a new temporary directory. The directory will be deleted on exit, if it only contains temp files and temp directories created after it. (To delete it on exit regardless of contents, call deleteDirectoryOnExit after constructing the file tree rooted at this directory. Note that createTempDirectory(..) is not much more helpful than mkdir() in this context (other than generating a new temp file name) because cleanup is a manual process.)

Parameters:
name - Non-unique portion of the name of the directory to create.
parent - Parent directory to contain the new directory
Returns:
File representing the directory that was created.
Throws:
IOException

deleteDirectory

@Deprecated
public static boolean deleteDirectory(File dir)
Deprecated. Use IOUtil.deleteRecursively(java.io.File) instead

Delete the given directory including any files and directories it contains.

Parameters:
dir - File object representing directory to delete. If, for some reason, this file object is not a directory, it will still be deleted.
Returns:
true if there were no problems in deleting. If it returns false, something failed and the directory contents likely at least partially still exist.

deleteDirectoryOnExit

@Deprecated
public static void deleteDirectoryOnExit(File dir)
Deprecated. Use IOUtil.deleteOnExitRecursively(java.io.File) instead

Instructs Java to recursively delete the given directory and its contents when the JVM exits.

Parameters:
dir - File object representing directory to delete. If, for some reason, this file object is not a directory, it will still be deleted.

packageExplore

public static LinkedList<String> packageExplore(String prefix,
                                                File root)
This function starts from the given directory and finds all packages within that directory

Parameters:
prefix - the package name of files in the given root
root - the directory to start exploring from
Returns:
a list of valid packages, excluding the root ("") package

renameFile

@Deprecated
public static boolean renameFile(File file,
                                            File dest)
Deprecated. Use IOUtil.attemptMove(java.io.File, java.io.File), which is equally Windows-friendly, instead.

Renames the given file to the given destination. Needed since Windows does not allow a rename to overwrite an existing file.

Parameters:
file - the file to rename
dest - the destination file
Returns:
true iff the rename was successful

saveFile

public static void saveFile(FileOps.FileSaver fileSaver)
                     throws IOException
This method writes files correctly; it takes care of catching errors, making backups, and keeping an unsuccessful file save from destroying the old file (unless a backup is made). It makes sure that the file to be saved is not read-only, throwing an IOException if it is. Note: if saving fails and a backup was being created, any existing backup will be destroyed (because the backup is written before saving begins, then moved back over the original file when saving fails). Since the old backup would have been destroyed anyway if saving had succeeded, this behavior is appropriate.

Parameters:
fileSaver - Keeps track of the name of the file to write, whether to back up the file, and has a method that actually performs the writing of the file
Throws:
IOException - if the saving or backing up of the file fails for any reason

convertToAbsolutePathEntries

@Deprecated
public static String convertToAbsolutePathEntries(String path)
Deprecated. Use IOUtil.parsePath(java.lang.String), IOUtil.getAbsoluteFiles(java.lang.Iterable), IOUtil.attemptAbsoluteFiles(java.lang.Iterable), and IOUtil.pathToString(java.lang.Iterable), as needed, instead.

Converts all path entries in a path string to absolute paths. The delimiter in the path string is the "path.separator" property. Empty entries are equivalent to "." and thus are converted to the value of "user.dir". Example: ".:drjava::/home/foo/junit.jar" with "user.dir" set to "/home/foo/bar" will be converted to "/home/foo/bar:/home/foo/bar/drjava:/home/foo/bar:/home/foo/junit.jar".

Parameters:
path - path string with entries to convert
Returns:
path string with all entries as absolute paths

getValidDirectory

public static File getValidDirectory(File origFile)
Return a valid directory for use, i.e. one that exists and is as "close" to the file specified. It is 1) file, if file is a directory and exists 2) the closest parent of file, if file is not a directory or does not exist 3) "user.home"

Returns:
a valid directory for use

toURL

public static URL toURL(File f)
                 throws MalformedURLException
Converts the abstract pathname for f into a URL. This method is included in class java.io.File as f.toURL(), but has been deprecated in Java 6.0 because escape characters on some systems are not handled correctly. The workaround, f.toURI().toURL(), is unsatisfactory because we rely on the old (broken) behavior: toURI() produces escape characters (for example, " " becomes "%20"), which remain in the name when we attempt to convert back to a filename. That is, f.toURI().toURL().getFile() may not be a valid path, even if f exists. (The correct solution is to avoid trying to convert from a URL to a File, because this conversion is not guaranteed to work.)

Throws:
MalformedURLException

makeWritable

public static boolean makeWritable(File roFile)
                            throws IOException
Throws:
IOException

moveRecursively

public static boolean moveRecursively(File f,
                                      File n)
Move f to n, recursively if necessary.

Parameters:
f - file or directory to move
n - new location and name for the file or directory
Returns:
true if successful