FileUtil

public class FileUtil
extends Object

java.lang.Object
   ↳ com.android.tradefed.util.FileUtil


A helper class for file related operations

Summary

Nested classes

class FileUtil.LowDiskSpaceException

Thrown if usable disk space is below minimum threshold. 

Constants

int FILESYSTEM_FILENAME_MAX_LENGTH

Public constructors

FileUtil()

Public methods

static String calculateMd5(File file)

Helper method to calculate md5 for a file.

static boolean chmod(File file, String perms)
static boolean chmodGroupRW(File file)

Performs a best effort attempt to make given file group readable and writable.

static boolean chmodGroupRWX(File file)

Performs a best effort attempt to make given file group executable, readable, and writable.

static boolean chmodRWXRecursively(File file)
static void closeZip(ZipFile zipFile)

This method is deprecated. Moved to closeZip(ZipFile).

static List<File> collectJars(File dir)

Returns all jar files found in given directory

static boolean compareFileContents(File file1, File file2)

Utility method to do byte-wise content comparison of two files.

static long convertSizeToBytes(String sizeString)

The inverse of convertToReadableSize(long).

static String convertToReadableSize(long sizeLong)

Convert the given file size in bytes to a more readable format in X.Y[KMGT] format.

static void copyFile(File origFile, File destFile)

A helper method that copies a file's contents to a local file

static File createNamedTempDir(String name)

Helper function to create a named directory inside your temp folder.

static File createTempDir(String prefix)

Helper function to create a temp directory in the system default temporary file directory.

static File createTempDir(String prefix, File parentDir)

Helper function to create a temp directory.

static File createTempFile(String prefix, String suffix, File parentDir)

Helper wrapper function around createTempFile(String, String, File) that audits for potential out of disk space scenario.

static File createTempFile(String prefix, String suffix)

Helper wrapper function around createTempFile(String, String) that audits for potential out of disk space scenario.

static File createTempFileForRemote(String remoteFilePath, File parentDir)

Helper method which constructs a unique file on temporary disk, whose name corresponds as closely as possible to the file name given by the remote file path

static File createZip(File dir)

This method is deprecated. Moved to createZip(File).

static void createZip(File dir, File zipFile)

This method is deprecated. Moved to createZip(File, File).

static void deleteFile(File file)

Try to delete a file.

static File extractFileFromZip(ZipFile zipFile, String filePath)

This method is deprecated. Moved to extractFileFromZip(ZipFile, String).

static void extractZip(ZipFile zipFile, File destDir)

This method is deprecated. Moved to extractZip(ZipFile, File).

static Set<File> findDirsUnder(File rootDir, File relativeParent)

Recursively find all directories under the given rootDir

static File findFile(File dir, String fileName)

Recursively search given directory for first file with given name

static Set<String> findFiles(File dir, String filter)
static String getBaseName(String fileName)

Gets the base name, without extension, of given file name.

static String getContentType(String filePath)

Get file's content type based it's extension.

static String getExtension(String fileName)

Gets the extension for given file name.

static File getFileForPath(File parentDir, String... pathSegments)

Helper method to build a system-dependent File

static String getPath(String... pathSegments)

Helper method to build a system-dependent relative path

static void gzipFile(File file, File gzipFile)

This method is deprecated. Moved to gzipFile(File, File).

static void hardlinkFile(File origFile, File destFile)

A helper method that hardlinks a file to another file

static boolean mkdirsRWX(File file)

Method to create a chain of directories, and set them all group execute/read/writable as they are created, by calling chmodGroupRWX(File).

static String readStringFromFile(File sourceFile)

A helper method for reading string data from a file

static void recursiveCopy(File sourceDir, File destDir)

Recursively copy folder contents.

static void recursiveDelete(File rootDir)

Recursively delete given file or directory and all its contents.

static void recursiveHardlink(File sourceDir, File destDir)

Recursively hardlink folder contents.

static void setReadableRecursive(File file)

Recursively set read and exec (if folder) permissions for given file.

static Set<PosixFilePermission> unixModeToPosix(int mode)

Converts an integer representing unix mode to a set of PosixFilePermissions

static void writeToFile(String inputString, File destFile)

A helper method for writing string data to file

static void writeToFile(InputStream input, File destFile, boolean append)

A helper method for writing stream data to file

static void writeToFile(InputStream input, File destFile)

A helper method for writing stream data to file

static void writeToFile(String inputString, File destFile, boolean append)

A helper method for writing or appending string data to file

Protected methods

static boolean chmodExists()

Internal helper to determine if 'chmod' is available on the system OS.

static void setChmodBinary(String chmodName)

Exposed for testing.

Constants

FILESYSTEM_FILENAME_MAX_LENGTH

int FILESYSTEM_FILENAME_MAX_LENGTH

Constant Value: 255 (0x000000ff)

Public constructors

FileUtil

FileUtil ()

Public methods

calculateMd5

String calculateMd5 (File file)

Helper method to calculate md5 for a file.

Returns
String md5 of the file
Throws
IOException

chmod

boolean chmod (File file, 
                String perms)

Parameters
file File
perms String
Returns
boolean

chmodGroupRW

boolean chmodGroupRW (File file)

Performs a best effort attempt to make given file group readable and writable.

Note that the execute permission is required to make directories accessible. See chmodGroupRWX(File).

If 'chmod' system command is not supported by underlying OS, will set file to writable by all.

Parameters
file File: the File to make owner and group writable
Returns
boolean true if file was successfully made group writable, false otherwise

chmodGroupRWX

boolean chmodGroupRWX (File file)

Performs a best effort attempt to make given file group executable, readable, and writable.

If 'chmod' system command is not supported by underlying OS, will attempt to set permissions for all users.

Parameters
file File: the File to make owner and group writable
Returns
boolean true if permissions were set successfully, false otherwise

chmodRWXRecursively

boolean chmodRWXRecursively (File file)

Parameters
file File
Returns
boolean

closeZip

void closeZip (ZipFile zipFile)

This method is deprecated.
Moved to closeZip(ZipFile).

Close an open ZipFile, ignoring any exceptions.

Parameters
zipFile ZipFile: the file to close

collectJars

List<File> collectJars (File dir)

Returns all jar files found in given directory

Parameters
dir File
Returns
List<File>

compareFileContents

boolean compareFileContents (File file1, 
                File file2)

Utility method to do byte-wise content comparison of two files.

Parameters
file1 File
file2 File
Returns
boolean true if file contents are identical
Throws
IOException

convertSizeToBytes

long convertSizeToBytes (String sizeString)

The inverse of convertToReadableSize(long). Converts the readable format described in convertToReadableSize(long) to a byte value.

Parameters
sizeString String: the string description of the size.
Returns
long the size in bytes
Throws
IllegalArgumentException if cannot recognize size

convertToReadableSize

String convertToReadableSize (long sizeLong)

Convert the given file size in bytes to a more readable format in X.Y[KMGT] format.

Parameters
sizeLong long: file size in bytes
Returns
String descriptive string of file size

copyFile

void copyFile (File origFile, 
                File destFile)

A helper method that copies a file's contents to a local file

Parameters
origFile File: the original file to be copied
destFile File: the destination file
Throws
IOException if failed to copy file

createNamedTempDir

File createNamedTempDir (String name)

Helper function to create a named directory inside your temp folder.

This directory will not have it's name randomized. If the directory already exists it will be returned.

Parameters
name String: The name of the directory to create in your tmp folder.
Returns
File the created directory
Throws
IOException

createTempDir

File createTempDir (String prefix)

Helper function to create a temp directory in the system default temporary file directory.

Parameters
prefix String: The prefix string to be used in generating the file's name; must be at least three characters long
Returns
File the created directory
Throws
IOException if file could not be created

createTempDir

File createTempDir (String prefix, 
                File parentDir)

Helper function to create a temp directory.

Parameters
prefix String: The prefix string to be used in generating the file's name; must be at least three characters long
parentDir File: The parent directory in which the directory is to be created. If null the system default temp directory will be used.
Returns
File the created directory
Throws
IOException if file could not be created

createTempFile

File createTempFile (String prefix, 
                String suffix, 
                File parentDir)

Helper wrapper function around createTempFile(String, String, File) that audits for potential out of disk space scenario.

Parameters
prefix String
suffix String
parentDir File
Returns
File
Throws
FileUtil.LowDiskSpaceException if disk space on partition is lower than minimum allowed
IOException

createTempFile

File createTempFile (String prefix, 
                String suffix)

Helper wrapper function around createTempFile(String, String) that audits for potential out of disk space scenario.

Parameters
prefix String
suffix String
Returns
File
Throws
FileUtil.LowDiskSpaceException if disk space on temporary partition is lower than minimum allowed
IOException

createTempFileForRemote

File createTempFileForRemote (String remoteFilePath, 
                File parentDir)

Helper method which constructs a unique file on temporary disk, whose name corresponds as closely as possible to the file name given by the remote file path

Parameters
remoteFilePath String: the '/' separated remote path to construct the name from
parentDir File: the parent directory to create the file in. null to use the default temporary directory
Returns
File
Throws
IOException

createZip

File createZip (File dir)

This method is deprecated.
Moved to createZip(File).

Utility method to create a temporary zip file containing the given directory and all its contents.

Parameters
dir File: the directory to zip
Returns
File a temporary zip File containing directory contents
Throws
IOException if failed to create zip file

createZip

void createZip (File dir, 
                File zipFile)

This method is deprecated.
Moved to createZip(File, File).

Utility method to create a zip file containing the given directory and all its contents.

Parameters
dir File: the directory to zip
zipFile File: the zip file to create - it should not already exist
Throws
IOException if failed to create zip file

deleteFile

void deleteFile (File file)

Try to delete a file. Intended for use when cleaning up in finally stanzas.

Parameters
file File: may be null.

extractFileFromZip

File extractFileFromZip (ZipFile zipFile, 
                String filePath)

This method is deprecated.
Moved to extractFileFromZip(ZipFile, String).

Utility method to extract one specific file from zip file into a tmp file

Parameters
zipFile ZipFile: the ZipFile to extract
filePath String: the filePath of to extract
Returns
File the File or null if not found
Throws
IOException if failed to extract file

extractZip

void extractZip (ZipFile zipFile, 
                File destDir)

This method is deprecated.
Moved to extractZip(ZipFile, File).

Utility method to extract entire contents of zip file into given directory

Parameters
zipFile ZipFile: the ZipFile to extract
destDir File: the local dir to extract file to
Throws
IOException if failed to extract file

findDirsUnder

Set<File> findDirsUnder (File rootDir, 
                File relativeParent)

Recursively find all directories under the given rootDir

Parameters
rootDir File: the root directory to search in
relativeParent File: An optional parent for all Files returned. If not specified, all Files will be relative to rootDir.
Returns
Set<File> An set of Files, representing all directories under rootDir, including rootDir itself. If rootDir is null, an empty set is returned.

findFile

File findFile (File dir, 
                String fileName)

Recursively search given directory for first file with given name

Parameters
dir File: the directory to search
fileName String: the name of the file to search for
Returns
File the File or null if it could not be found

findFiles

Set<String> findFiles (File dir, 
                String filter)

Parameters
dir File
filter String
Returns
Set<String>
Throws
IOException

getBaseName

String getBaseName (String fileName)

Gets the base name, without extension, of given file name.

e.g. getBaseName("file.txt") will return "file"

Returns
String the base name

getContentType

String getContentType (String filePath)

Get file's content type based it's extension.

Parameters
filePath String: the file path
Returns
String content type

getExtension

String getExtension (String fileName)

Gets the extension for given file name.

Returns
String the extension or empty String if file has no extension

getFileForPath

File getFileForPath (File parentDir, 
                String... pathSegments)

Helper method to build a system-dependent File

Parameters
parentDir File: the parent directory to use.
pathSegments String: the relative path segments to use
Returns
File the File representing given path, with each pathSegment separated by separatorChar

getPath

String getPath (String... pathSegments)

Helper method to build a system-dependent relative path

Parameters
pathSegments String: the relative path segments to use
Returns
String the String representing given path, with each pathSegment separated by separatorChar

gzipFile

void gzipFile (File file, 
                File gzipFile)

This method is deprecated.
Moved to gzipFile(File, File).

Helper method to create a gzipped version of a single file.

Parameters
file File: the original file
gzipFile File: the file to place compressed contents in
Throws
IOException
IOException

hardlinkFile

void hardlinkFile (File origFile, 
                File destFile)

A helper method that hardlinks a file to another file

Parameters
origFile File: the original file
destFile File: the destination file
Throws
IOException if failed to hardlink file

mkdirsRWX

boolean mkdirsRWX (File file)

Method to create a chain of directories, and set them all group execute/read/writable as they are created, by calling chmodGroupRWX(File). Essentially a version of mkdirs() that also runs chmod(File, String).

Parameters
file File: the name of the directory to create, possibly with containing directories that don't yet exist.
Returns
boolean true if file exists and is a directory, false otherwise.

readStringFromFile

String readStringFromFile (File sourceFile)

A helper method for reading string data from a file

Parameters
sourceFile File: the file to read from
Returns
String
Throws
IOException
FileNotFoundException
IOException

recursiveCopy

void recursiveCopy (File sourceDir, 
                File destDir)

Recursively copy folder contents.

Only supports copying of files and directories - symlinks are not copied. If the destination directory does not exist, it will be created.

Parameters
sourceDir File: the folder that contains the files to copy
destDir File: the destination folder
Throws
IOException

recursiveDelete

void recursiveDelete (File rootDir)

Recursively delete given file or directory and all its contents.

Parameters
rootDir File: the directory or file to be deleted; can be null

recursiveHardlink

void recursiveHardlink (File sourceDir, 
                File destDir)

Recursively hardlink folder contents.

Only supports copying of files and directories - symlinks are not copied. If the destination directory does not exist, it will be created.

Parameters
sourceDir File: the folder that contains the files to copy
destDir File: the destination folder
Throws
IOException

setReadableRecursive

void setReadableRecursive (File file)

Recursively set read and exec (if folder) permissions for given file.

Parameters
file File

unixModeToPosix

Set<PosixFilePermission> unixModeToPosix (int mode)

Converts an integer representing unix mode to a set of PosixFilePermissions

Parameters
mode int
Returns
Set<PosixFilePermission>

writeToFile

void writeToFile (String inputString, 
                File destFile)

A helper method for writing string data to file

Parameters
inputString String: the input String
destFile File: the destination file to write to
Throws
IOException

writeToFile

void writeToFile (InputStream input, 
                File destFile, 
                boolean append)

A helper method for writing stream data to file

Parameters
input InputStream: the unbuffered input stream
destFile File: the destination file to write or append to
append boolean: append to end of file if true, overwrite otherwise
Throws
IOException

writeToFile

void writeToFile (InputStream input, 
                File destFile)

A helper method for writing stream data to file

Parameters
input InputStream: the unbuffered input stream
destFile File: the destination file to write to
Throws
IOException

writeToFile

void writeToFile (String inputString, 
                File destFile, 
                boolean append)

A helper method for writing or appending string data to file

Parameters
inputString String: the input String
destFile File: the destination file to write or append to
append boolean: append to end of file if true, overwrite otherwise
Throws
IOException

Protected methods

chmodExists

boolean chmodExists ()

Internal helper to determine if 'chmod' is available on the system OS.

Returns
boolean

setChmodBinary

void setChmodBinary (String chmodName)

Exposed for testing. Allows to modify the chmod binary name we look for, in order to tests system with no chmod support.

Parameters
chmodName String