Package ptolemy.util

Class FileUtilities


  • public class FileUtilities
    extends java.lang.Object
    A collection of utilities for manipulating files These utilities do not depend on any other ptolemy.* packages.
    Since:
    Ptolemy II 4.0
    Version:
    $Id$
    Author:
    Christopher Brooks
    Pt.AcceptedRating:
    Green (cxh)
    Pt.ProposedRating:
    Green (cxh)
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      static class  FileUtilities.StreamAndURL
      A class that contains an InputStream and a URL so that we don't have to follow redirects twice.
    • Field Summary

      Fields 
      Modifier and Type Field Description
      static java.io.BufferedReader STD_IN
      Standard in as a reader, which will be non-null only after a call to openForReading("System.in").
      static java.io.PrintWriter STD_OUT
      Standard out as a writer, which will be non-null only after a call to openForWriting("System.out").
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static boolean binaryCopyURLToFile​(java.net.URL sourceURL, java.io.File destinationFile)
      Copy sourceURL to destinationFile without doing any byte conversion.
      static byte[] binaryReadURLToByteArray​(java.net.URL sourceURL)
      Read a sourceURL without doing any byte conversion.
      static java.lang.String createLink​(java.nio.file.Path newLink, java.nio.file.Path temporary, java.nio.file.Path target)
      Create a link.
      static boolean deleteDirectory​(java.io.File directory)
      Delete a directory.
      static boolean deleteDirectory​(java.lang.String filepath)
      Delete a directory and all of its content.
      static void extractJarFile​(java.lang.String jarFileName, java.lang.String directoryName)
      Extract a jar file into a directory.
      static void extractJarFileIfNecessary​(java.lang.String targetFileName, java.lang.String directoryName)
      If necessary, unjar the entire jar file that contains a target file.
      static java.net.URL followRedirects​(java.net.URL url)
      Given a URL, if it starts with http, the follow up to 10 redirects.
      static java.lang.String getFileAsString​(java.lang.String path)
      Return the string contents of the file at the specified location.
      static boolean inPath​(java.lang.String command)
      Return true if the command can be found in the directories listed in the directories contained in the PATH environment variable.
      static void main​(java.lang.String[] args)
      Extract the contents of a jar file.
      static java.io.File nameToFile​(java.lang.String name, java.net.URI base)
      Given a file name or URL, construct a java.io.File object that refers to the file name or URL.
      static java.net.URL nameToURL​(java.lang.String name, java.net.URI baseDirectory, java.lang.ClassLoader classLoader)
      Given a file or URL name, return as a URL.
      static java.io.BufferedReader openForReading​(java.lang.String name, java.net.URI base, java.lang.ClassLoader classLoader)
      Open the specified file for reading.
      static java.io.Writer openForWriting​(java.lang.String name, java.net.URI base, boolean append)
      Open the specified file for writing or appending.
      static java.io.InputStream openStreamFollowingRedirects​(java.net.URL url)
      Given a URL, open a stream.
      static FileUtilities.StreamAndURL openStreamFollowingRedirectsReturningBoth​(java.net.URL url)
      Given a URL, open a stream and return an object containing both the inputStream and the possibly redirected URL.
      static java.lang.String readFromInputStream​(java.io.InputStream stream)
      Utility method to read a string from an input stream.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • STD_IN

        public static java.io.BufferedReader STD_IN
        Standard in as a reader, which will be non-null only after a call to openForReading("System.in").
      • STD_OUT

        public static java.io.PrintWriter STD_OUT
        Standard out as a writer, which will be non-null only after a call to openForWriting("System.out").
    • Method Detail

      • binaryCopyURLToFile

        public static boolean binaryCopyURLToFile​(java.net.URL sourceURL,
                                                  java.io.File destinationFile)
                                           throws java.io.IOException
        Copy sourceURL to destinationFile without doing any byte conversion.
        Parameters:
        sourceURL - The source URL
        destinationFile - The destination File.
        Returns:
        true if the file was copied, false if the file was not copied because the sourceURL and the destinationFile refer to the same file.
        Throws:
        java.io.IOException - If the source file does not exist.
      • binaryReadURLToByteArray

        public static byte[] binaryReadURLToByteArray​(java.net.URL sourceURL)
                                               throws java.io.IOException
        Read a sourceURL without doing any byte conversion.
        Parameters:
        sourceURL - The source URL
        Returns:
        The array of bytes read from the URL.
        Throws:
        java.io.IOException - If the source URL does not exist.
      • createLink

        public static java.lang.String createLink​(java.nio.file.Path newLink,
                                                  java.nio.file.Path temporary,
                                                  java.nio.file.Path target)
                                           throws java.io.IOException
        Create a link.
        Parameters:
        newLink - the link to be created
        temporary - the path to the temporary location where the directory to be replaced by the link should be placed.
        target - the target of the link to be created.
        Returns:
        A status message
        Throws:
        java.io.IOException - If there are problems creating the link
      • deleteDirectory

        public static boolean deleteDirectory​(java.io.File directory)
        Delete a directory.
        Parameters:
        directory - the File naming the directory.
        Returns:
        true if the toplevel directory was deleted or does not exist.
      • deleteDirectory

        public static boolean deleteDirectory​(java.lang.String filepath)
        Delete a directory and all of its content.
        Parameters:
        filepath - The path for the directory or file to be deleted.
        Returns:
        false if one or more files or directories cannot be deleted.
      • extractJarFile

        public static void extractJarFile​(java.lang.String jarFileName,
                                          java.lang.String directoryName)
                                   throws java.io.IOException
        Extract a jar file into a directory. This is a trivial implementation of the jar -xf command.
        Parameters:
        jarFileName - The name of the jar file to extract
        directoryName - The name of the directory. If this argument is null, then the files are extracted in the current directory.
        Throws:
        java.io.IOException - If the jar file cannot be opened, or if there are problems extracting the contents of the jar file
      • extractJarFileIfNecessary

        public static void extractJarFileIfNecessary​(java.lang.String targetFileName,
                                                     java.lang.String directoryName)
                                              throws java.io.IOException
        If necessary, unjar the entire jar file that contains a target file.
        Parameters:
        targetFileName - If the file exists relative to the directoryName, then do nothing. Otherwise, look for the targetFile in the classpath and unjar the jar file in which it is found in the directory named by the directoryName parameter.
        directoryName - The name of the directory in which to search for the file named by the targetFileName parameter and in which the jar file is possibly unjared.
        Throws:
        java.io.IOException - If there is problem finding the target file or extracting the jar file.
      • followRedirects

        public static java.net.URL followRedirects​(java.net.URL url)
                                            throws java.io.IOException
        Given a URL, if it starts with http, the follow up to 10 redirects.

        If the URL is null or does not start with "http", then return the URL.

        Parameters:
        url - The URL to be followed.
        Returns:
        The new URL if any.
        Throws:
        java.io.IOException - If there is a problem opening the URL or if there are more than 10 redirects.
      • getFileAsString

        public static java.lang.String getFileAsString​(java.lang.String path)
                                                throws java.io.IOException
        Return the string contents of the file at the specified location.
        Parameters:
        path - The location.
        Returns:
        The contents as a string, assuming the default encoding of this JVM (probably utf-8).
        Throws:
        java.io.IOException - If the file cannot be read.
      • inPath

        public static boolean inPath​(java.lang.String command)
        Return true if the command can be found in the directories listed in the directories contained in the PATH environment variable.
        Parameters:
        command - The command for which to search.
        Returns:
        True if the command can be found in $PATH
      • main

        public static void main​(java.lang.String[] args)
        Extract the contents of a jar file.
        Parameters:
        args - An array of arguments. The first argument names the jar file to be extracted. The first argument is required. The second argument names the directory in which to extract the files from the jar file. The second argument is optional.
      • nameToFile

        public static java.io.File nameToFile​(java.lang.String name,
                                              java.net.URI base)
        Given a file name or URL, construct a java.io.File object that refers to the file name or URL. This method first attempts to directly use the file name to construct the File. If the resulting File is a relative pathname, then it is resolved relative to the specified base URI, if there is one. If there is no such base URI, then it simply returns the relative File object. See the java.io.File documentation for a details about relative and absolute pathnames.

        If the name begins with "xxxxxxCLASSPATHxxxxxx" or "$CLASSPATH" then search for the file relative to the classpath.

        Note that "xxxxxxCLASSPATHxxxxxx" is the value of the globally defined constant $CLASSPATH available in the Ptolemy II expression language.

        If the name begins with $CLASSPATH or "xxxxxxCLASSPATHxxxxxx" but that name cannot be found in the classpath, the value of the ptolemy.ptII.dir property is substituted in.

        The file need not exist for this method to succeed. Thus, this method can be used to determine whether a file with a given name exists, prior to calling openForWriting(), for example.

        This method is similar to nameToURL(String, URI, ClassLoader) except that in this method, the file or URL must be readable. Usually, this method is use for write a file and nameToURL(String, URI, ClassLoader) is used for reading.

        Parameters:
        name - The file name or URL.
        base - The base for relative URLs.
        Returns:
        A File, or null if the filename argument is null or an empty string.
        See Also:
        nameToURL(String, URI, ClassLoader)
      • nameToURL

        public static java.net.URL nameToURL​(java.lang.String name,
                                             java.net.URI baseDirectory,
                                             java.lang.ClassLoader classLoader)
                                      throws java.io.IOException
        Given a file or URL name, return as a URL. If the file name is relative, then it is interpreted as being relative to the specified base directory. If the name begins with "xxxxxxCLASSPATHxxxxxx" or "$CLASSPATH" then search for the file relative to the classpath.

        Note that "xxxxxxCLASSPATHxxxxxx" is the value of the globally defined constant $CLASSPATH available in the Ptolemy II expression language. II expression language.

        If no file is found, then throw an exception.

        This method is similar to nameToFile(String, URI) except that in this method, the file or URL must be readable. Usually, this method is use for reading a file and is used for writing nameToFile(String, URI).

        Parameters:
        name - The name of a file or URL.
        baseDirectory - The base directory for relative file names, or null to specify none.
        classLoader - The class loader to use to locate system resources, or null to use the system class loader that was used to load this class.
        Returns:
        A URL, or null if the name is null or the empty string.
        Throws:
        java.io.IOException - If the file cannot be read, or if the file cannot be represented as a URL (e.g. System.in), or the name specification cannot be parsed.
        See Also:
        nameToFile(String, URI)
      • openForReading

        public static java.io.BufferedReader openForReading​(java.lang.String name,
                                                            java.net.URI base,
                                                            java.lang.ClassLoader classLoader)
                                                     throws java.io.IOException
        Open the specified file for reading. If the specified name is "System.in", then a reader from standard in is returned. If the name begins with "$CLASSPATH" or "xxxxxxCLASSPATHxxxxxx", then the name is passed to nameToURL(String, URI, ClassLoader) If the file name is not absolute, the it is assumed to be relative to the specified base URI.
        Parameters:
        name - File name.
        base - The base URI for relative references.
        classLoader - The class loader to use to locate system resources, or null to use the system class loader that was used to load this class.
        Returns:
        If the name is null or the empty string, then null is returned, otherwise a buffered reader is returned.
        Throws:
        java.io.IOException - If the file cannot be opened.
        See Also:
        nameToURL(String, URI, ClassLoader)
      • openForWriting

        public static java.io.Writer openForWriting​(java.lang.String name,
                                                    java.net.URI base,
                                                    boolean append)
                                             throws java.io.IOException
        Open the specified file for writing or appending. If the specified name is "System.out", then a writer to standard out is returned; otherwise, pass the name and base to nameToFile(String, URI) and create a file writer. If the file does not exist, then create it. If the file name is not absolute, the it is assumed to be relative to the specified base directory. If permitted, this method will return a Writer that will simply overwrite the contents of the file. It is up to the user of this method to check whether this is OK (by first calling nameToFile(String, URI) and calling exists() on the returned value).
        Parameters:
        name - File name.
        base - The base URI for relative references.
        append - If true, then append to the file rather than overwriting.
        Returns:
        If the name is null or the empty string, then null is returned, otherwise a writer is returned.
        Throws:
        java.io.IOException - If the file cannot be opened or created.
      • openStreamFollowingRedirects

        public static java.io.InputStream openStreamFollowingRedirects​(java.net.URL url)
                                                                throws java.io.IOException
        Given a URL, open a stream.

        If the URL starts with "http", then follow up to 10 redirects and return the the final HttpURLConnection.

        If the URL does not start with "http", then call URL.openStream().

        Parameters:
        url - The URL to be opened.
        Returns:
        The input stream
        Throws:
        java.io.IOException - If there is a problem opening the URL or if there are more than 10 redirects.
      • openStreamFollowingRedirectsReturningBoth

        public static FileUtilities.StreamAndURL openStreamFollowingRedirectsReturningBoth​(java.net.URL url)
                                                                                    throws java.io.IOException
        Given a URL, open a stream and return an object containing both the inputStream and the possibly redirected URL.

        If the URL starts with "http", then follow up to 10 redirects and return the the final HttpURLConnection.

        If the URL does not start with "http", then call URL.openStream().

        Parameters:
        url - The URL to be opened.
        Returns:
        The input stream
        Throws:
        java.io.IOException - If there is a problem opening the URL or if there are more than 10 redirects.
      • readFromInputStream

        public static java.lang.String readFromInputStream​(java.io.InputStream stream)
                                                    throws java.io.IOException
        Utility method to read a string from an input stream.
        Parameters:
        stream - The stream.
        Returns:
        The string.
        Throws:
        java.io.IOException - If the stream cannot be read.