Class FileUtils


  • public class FileUtils
    extends org.apache.commons.io.FileUtils
    Contains utility methods for reading/writing files while handling encodings and other issues.
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      protected static class  FileUtils.FileNameComparator
      Compares file objects.
    • Field Summary

      Fields 
      Modifier and Type Field Description
      static java.lang.String ENCODING_UTF_8
      The UTF-8 encoding constant (equal to "UTF-8").
      static java.lang.String LINE_SEP
      The line separator equal to system property "line.separator".
      • Fields inherited from class org.apache.commons.io.FileUtils

        EMPTY_FILE_ARRAY, ONE_EB, ONE_EB_BI, ONE_GB, ONE_GB_BI, ONE_KB, ONE_KB_BI, ONE_MB, ONE_MB_BI, ONE_PB, ONE_PB_BI, ONE_TB, ONE_TB_BI, ONE_YB, ONE_ZB
    • Constructor Summary

      Constructors 
      Modifier Constructor Description
      protected FileUtils()
      The default constructor.
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static boolean cleanDirectoryIfNoFiles​(java.io.File dir)
      Deletes the contents of a given directory if there are no files in the directory itself or in any of its descendant subdirectories.
      static void cleanEmptyDirectories​(java.io.File dir)
      Recursively walks the directory, deleting it if it contains no files or just empty subdirectories.
      static void cleanup​(java.io.File directory, java.lang.String[] extensions, long olderThan)
      Deletes files with the extensions in a given directory that are older than the date(long)
      static void copyDirectory​(java.io.File src, java.io.File dest)
      Copies a directory
      static int countFiles​(java.io.File directory, java.lang.String... extensions)
      Counts files in a directory
      static java.io.File createDirectory​(java.io.File directory)
      Creates the directory and any necessary parent directories.
      static java.io.File createDirectory​(java.lang.String directory)
      Creates the directory and any necessary parent directories.
      static java.io.InputStream decompress​(java.io.InputStream input)
      Will optionally apply decompression to input if compressed.
      static void deleteDirectoryOrFile​(java.io.File f)
      Tries to delete a file or directory immediately.
      static boolean deleteFile​(java.io.File f)
      Tries to delete a file immediately.
      static java.io.File deleteFileAndParentIfEmpty​(java.io.File f)
      If the parent of f will be empty after this file is deleted, then delete both.
      static boolean directoryContainsFile​(java.io.File dir, java.io.File file)  
      static java.io.File getAttivioTempDirectory()
      Gets the temp file directory.
      static java.lang.String getFileExtension​(java.lang.String path, boolean includeDot)
      Gets the file extension, given the file path.
      static java.lang.String[] getFileNameParts​(java.lang.String fileName)
      Splits a filename into two constituent parts, the short name and the extension, if any.
      static java.lang.String getPrettySize​(java.io.File f)
      Gets a "pretty" (user-friendly) size string for the size of a given file.
      static void moveFile​(java.io.File srcFile, java.io.File destFile)
      Moves a file from one directory to another, acts as a rename If destination file exists will delete the existing file and then move
      static java.io.Reader newFileReader​(java.lang.String filePath)
      Gets a Reader from a file in UTF-8.
      static java.io.InputStream openCompressedInputStream​(java.io.File file)
      Opens an InputStream for the possibly compressed specified file.
      static java.io.InputStream openCompressedInputStream​(java.net.URI uri)
      Opens an InputStream for the possibly compressed specified uri.
      static java.lang.String pathJoin​(java.lang.String... args)
      Joins multiple sub-paths into a single path.
      static java.lang.String readFileAsText​(java.io.File f)
      Reads a file in the default encoding ENCODING_UTF_8.
      static void renameFile​(java.io.File src, java.io.File dest)
      Renames a file, deleting destination and retrying if rename fails.
      static long size​(java.io.File file)
      Gets the size of a file or directory recursively walking all subdirectories.
      static java.io.File[] sortFileByName​(java.io.File[] files)
      Sorts files in alphabetical order.
      static void sync​(java.io.File file)
      Do everything possible to sync file to stable storage.
      static void sync​(java.io.File file, int retries)
      Do everything possible to sync file to stable storage.
      static void unjar​(java.io.File jarFile, java.io.File dest)
      Unzips a jar file into the destination folder;
      static void unzip​(java.io.File zipFile, java.io.File dest)
      Unzips a zip file into the destination folder;
      static void writeFile​(java.io.File f, java.lang.String contents)
      Writes out the contents of a file in the default encoding ENCODING_UTF_8.
      static void writeFile​(java.lang.String file, java.lang.String contents)
      Writes out the contents of a file in the default encoding ENCODING_UTF_8.
      • Methods inherited from class org.apache.commons.io.FileUtils

        byteCountToDisplaySize, byteCountToDisplaySize, checksum, checksumCRC32, cleanDirectory, contentEquals, contentEqualsIgnoreEOL, convertFileCollectionToFileArray, copyDirectory, copyDirectory, copyDirectory, copyDirectoryToDirectory, copyFile, copyFile, copyFile, copyFileToDirectory, copyFileToDirectory, copyInputStreamToFile, copyURLToFile, copyURLToFile, deleteDirectory, deleteQuietly, directoryContains, forceDelete, forceDeleteOnExit, forceMkdir, getFile, getFile, getTempDirectory, getTempDirectoryPath, getUserDirectory, getUserDirectoryPath, isFileNewer, isFileNewer, isFileNewer, isFileOlder, isFileOlder, isFileOlder, isSymlink, iterateFiles, iterateFiles, iterateFilesAndDirs, lineIterator, lineIterator, listFiles, listFiles, listFilesAndDirs, moveDirectory, moveDirectoryToDirectory, moveFileToDirectory, moveToDirectory, openInputStream, openOutputStream, openOutputStream, readFileToByteArray, readFileToString, readFileToString, readFileToString, readLines, readLines, readLines, sizeOf, sizeOfAsBigInteger, sizeOfDirectory, sizeOfDirectoryAsBigInteger, toFile, toFiles, touch, toURLs, waitFor, write, write, write, write, write, write, writeByteArrayToFile, writeByteArrayToFile, writeLines, writeLines, writeLines, writeLines, writeLines, writeLines, writeLines, writeLines, writeStringToFile, writeStringToFile, writeStringToFile, writeStringToFile, writeStringToFile, writeStringToFile
      • Methods inherited from class java.lang.Object

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

      • LINE_SEP

        public static final java.lang.String LINE_SEP
        The line separator equal to system property "line.separator".
      • ENCODING_UTF_8

        public static final java.lang.String ENCODING_UTF_8
        The UTF-8 encoding constant (equal to "UTF-8").
        See Also:
        Constant Field Values
    • Constructor Detail

      • FileUtils

        protected FileUtils()
        The default constructor. (Hidden).
    • Method Detail

      • readFileAsText

        public static java.lang.String readFileAsText​(java.io.File f)
                                               throws java.io.IOException
        Reads a file in the default encoding ENCODING_UTF_8.
        Parameters:
        f - file to read
        Returns:
        the contents of the file
        Throws:
        java.io.IOException - if an error occours while reading a file
      • renameFile

        public static void renameFile​(java.io.File src,
                                      java.io.File dest)
                               throws java.io.IOException
        Renames a file, deleting destination and retrying if rename fails.
        Parameters:
        src - the source file
        dest - the destination file
        Throws:
        java.io.IOException
      • openCompressedInputStream

        public static java.io.InputStream openCompressedInputStream​(java.io.File file)
                                                             throws java.io.IOException
        Opens an InputStream for the possibly compressed specified file.

        If the file is gzipped, it will be wrapped in a GZIPInputStream.

        Parameters:
        file - the file to open.
        Returns:
        an InputStream for reading file
        Throws:
        java.io.IOException - if opening file fails.
      • openCompressedInputStream

        public static java.io.InputStream openCompressedInputStream​(java.net.URI uri)
                                                             throws java.io.IOException
        Opens an InputStream for the possibly compressed specified uri.

        If the uri is gzipped, it will be wrapped in a GZIPInputStream.

        Parameters:
        uri -
        Returns:
        an InputStream for reading the uri
        Throws:
        java.io.IOException - if opening file fails.
      • decompress

        public static java.io.InputStream decompress​(java.io.InputStream input)
                                              throws java.io.IOException
        Will optionally apply decompression to input if compressed.

        NOTE: assumes input is positioned at beginning of stream.

        NOTE: currently only supports gzip compression.

        Throws:
        java.io.IOException
      • writeFile

        public static void writeFile​(java.lang.String file,
                                     java.lang.String contents)
                              throws java.io.IOException
        Writes out the contents of a file in the default encoding ENCODING_UTF_8.
        Parameters:
        file - the file name to write to, parent directories are created if necessary
        contents - the content to write to the file
        Throws:
        java.io.IOException - if an error occours while weriting the file
      • writeFile

        public static void writeFile​(java.io.File f,
                                     java.lang.String contents)
                              throws java.io.IOException
        Writes out the contents of a file in the default encoding ENCODING_UTF_8.
        Parameters:
        f - the file to write to, parent directories are created if necessary
        contents - the content to write to the file
        Throws:
        java.io.IOException - if an error occours while weriting the file
      • deleteDirectoryOrFile

        public static void deleteDirectoryOrFile​(java.io.File f)
                                          throws java.io.IOException
        Tries to delete a file or directory immediately. If that fails, zero's out any files and flag them for delete when the jvm exits.
        Parameters:
        f - file to delete
        Throws:
        java.io.IOException
      • deleteFile

        public static boolean deleteFile​(java.io.File f)
                                  throws java.io.IOException
        Tries to delete a file immediately. If that fails, flag it for delete when the JVM exits.
        Parameters:
        f - file to delete
        Returns:
        true if file was deleted or did not exist, false if scheduled for deletion
        Throws:
        java.io.IOException
      • deleteFileAndParentIfEmpty

        public static java.io.File deleteFileAndParentIfEmpty​(java.io.File f)
                                                       throws java.io.IOException
        If the parent of f will be empty after this file is deleted, then delete both. Returns parent directory if it was deleted
        Parameters:
        f -
        Returns:
        the parent file if it was deleted, null otherwise
        Throws:
        java.io.IOException
      • createDirectory

        public static java.io.File createDirectory​(java.io.File directory)
                                            throws java.io.IOException
        Creates the directory and any necessary parent directories.
        Parameters:
        directory - directory to create
        Returns:
        handle to newly created directory
        Throws:
        java.io.IOException
      • createDirectory

        public static java.io.File createDirectory​(java.lang.String directory)
                                            throws java.io.IOException
        Creates the directory and any necessary parent directories.
        Parameters:
        directory - directory to create
        Returns:
        handle to newly created directory
        Throws:
        java.io.IOException
      • sortFileByName

        public static java.io.File[] sortFileByName​(java.io.File[] files)
        Sorts files in alphabetical order.
        Parameters:
        files - the array of file objects to sort
        Returns:
        the sorted array
      • copyDirectory

        public static void copyDirectory​(java.io.File src,
                                         java.io.File dest)
                                  throws java.io.IOException
        Copies a directory
        Parameters:
        src - the source
        dest - the destination
        Throws:
        java.io.IOException
      • moveFile

        public static void moveFile​(java.io.File srcFile,
                                    java.io.File destFile)
                             throws java.io.IOException
        Moves a file from one directory to another, acts as a rename If destination file exists will delete the existing file and then move
        Parameters:
        srcFile - the source, must exist and not be a directory
        destFile - the destination, must exist and not be a directory
        Throws:
        java.io.IOException
      • countFiles

        public static int countFiles​(java.io.File directory,
                                     java.lang.String... extensions)
                              throws java.io.IOException
        Counts files in a directory
        Parameters:
        directory - the directory
        extensions - any extensions to filter files by
        Returns:
        the count
        Throws:
        java.io.IOException
      • getPrettySize

        public static java.lang.String getPrettySize​(java.io.File f)
        Gets a "pretty" (user-friendly) size string for the size of a given file.
        Parameters:
        f - the file
        Returns:
        the size as a user-friendly string
      • getFileExtension

        public static java.lang.String getFileExtension​(java.lang.String path,
                                                        boolean includeDot)
        Gets the file extension, given the file path. The returned extension is normalized to lower case.
        Parameters:
        path - the file path
        includeDot - if true, the dot is included in the returned extension
        Returns:
        the extension, or null if the path has no extension
      • getFileNameParts

        public static java.lang.String[] getFileNameParts​(java.lang.String fileName)
        Splits a filename into two constituent parts, the short name and the extension, if any.
        Parameters:
        fileName -
        Returns:
        a string array whose 0-th element is the short name (with no extension) and the first element is the extension; if no extension is present, the first element is set to an empty string
      • pathJoin

        public static java.lang.String pathJoin​(java.lang.String... args)
        Joins multiple sub-paths into a single path.
        Parameters:
        args - the sub-paths
        Returns:
        the path
      • size

        public static long size​(java.io.File file)
        Gets the size of a file or directory recursively walking all subdirectories.
      • newFileReader

        public static java.io.Reader newFileReader​(java.lang.String filePath)
                                            throws java.io.FileNotFoundException
        Gets a Reader from a file in UTF-8.
        Throws:
        java.io.FileNotFoundException
      • sync

        public static void sync​(java.io.File file)
                         throws java.io.IOException
        Do everything possible to sync file to stable storage.
        Throws:
        java.io.IOException
      • sync

        public static void sync​(java.io.File file,
                                int retries)
                         throws java.io.IOException
        Do everything possible to sync file to stable storage.
        Throws:
        java.io.IOException
      • getAttivioTempDirectory

        public static final java.io.File getAttivioTempDirectory()
                                                          throws java.io.IOException
        Gets the temp file directory.
        Throws:
        java.io.IOException
      • cleanDirectoryIfNoFiles

        public static boolean cleanDirectoryIfNoFiles​(java.io.File dir)
                                               throws java.io.IOException
        Deletes the contents of a given directory if there are no files in the directory itself or in any of its descendant subdirectories.
        Parameters:
        dir - the directory to clean
        Throws:
        java.io.IOException
      • cleanup

        public static void cleanup​(java.io.File directory,
                                   java.lang.String[] extensions,
                                   long olderThan)
                            throws java.io.IOException
        Deletes files with the extensions in a given directory that are older than the date(long)
        Parameters:
        directory - the directory to clean
        extensions - of files, extension should not include the period prefix
        olderThan - long time files must be older to be deleted 0 means remove immediately
        Throws:
        java.io.IOException
      • cleanEmptyDirectories

        public static final void cleanEmptyDirectories​(java.io.File dir)
                                                throws java.io.IOException
        Recursively walks the directory, deleting it if it contains no files or just empty subdirectories.
        Parameters:
        dir -
        Throws:
        java.io.IOException
      • directoryContainsFile

        public static boolean directoryContainsFile​(java.io.File dir,
                                                    java.io.File file)
        Parameters:
        dir -
        file -
        Returns:
        true if file is contained within dir. this is done by examining paths only
      • unjar

        public static void unjar​(java.io.File jarFile,
                                 java.io.File dest)
                          throws java.io.IOException
        Unzips a jar file into the destination folder;
        Parameters:
        jarFile -
        dest -
        Throws:
        java.io.IOException
      • unzip

        public static void unzip​(java.io.File zipFile,
                                 java.io.File dest)
                          throws java.io.IOException
        Unzips a zip file into the destination folder;
        Parameters:
        zipFile -
        dest -
        Throws:
        java.io.IOException