In this article, we will discuss 20 useful commonly used file utility methods. You can use these file utility methods in your day to day project work. I found these utility methods are useful and I thought I should share with you all.
Utility methods perform common, often reused functions and they don't require to have object level state, that is they tend to be global functions.
You should utilize below Java utility classes and methods in your projects:
Executors Utility Class in Java
java.util.Arrays Class
Java String Utility Class
java.util.Collections Class
Java Custom CollectionUtils Class
18 Useful Collections Utility Methods
27 Useful String Utility Methods
Let's list 20 useful and commonly used file utility methods.
java.util.Arrays Class
Java String Utility Class
java.util.Collections Class
Java Custom CollectionUtils Class
18 Useful Collections Utility Methods
27 Useful String Utility Methods
20 File Utility Methods
Get the last modified given file date
/**
* get last modified given file date
* @param file
* @return
*/
public static long getLastModifiedDate(File file) {
return file.lastModified();
}
/**
* get last modified given file date
* @param file
* @return
*/
public static long getLastModifiedDate(File file) {
return file.lastModified();
}
Get file size in human-readable size using SI prefix - B,KB,MB,GB,TB
/**
* Given the size of a file outputs as human readable size using SI prefix.
* <i>Base 1024</i>
* @param size Size in bytes of a given File.
* @return SI String representing the file size (B,KB,MB,GB,TB).
*/
public static String readableFileSize(long size) {
if (size <= 0) {
return "0";
}
final String[] units = new String[] {
"B",
"KB",
"MB",
"GB",
"TB"
};
int digitGroups = (int)(Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) +
" " + units[digitGroups];
}
/**
* Given the size of a file outputs as human readable size using SI prefix.
* <i>Base 1024</i>
* @param size Size in bytes of a given File.
* @return SI String representing the file size (B,KB,MB,GB,TB).
*/
public static String readableFileSize(long size) {
if (size <= 0) {
return "0";
}
final String[] units = new String[] {
"B",
"KB",
"MB",
"GB",
"TB"
};
int digitGroups = (int)(Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) +
" " + units[digitGroups];
}
Get file extension such as "txt","png","pdf"
/**
* Get file extension such as "txt","png","pdf"
* @param file
* @return
*/
public static String getFileExtension(File file) {
String fileName = file.getName();
if (fileName.lastIndexOf('.') != -1 && fileName.lastIndexOf('.') != 0) {
return fileName.substring(fileName.lastIndexOf('.') + 1);
} else {
return "File don't have extension";
}
}
/**
* Get file extension such as "txt","png","pdf"
* @param file
* @return
*/
public static String getFileExtension(File file) {
String fileName = file.getName();
if (fileName.lastIndexOf('.') != -1 && fileName.lastIndexOf('.') != 0) {
return fileName.substring(fileName.lastIndexOf('.') + 1);
} else {
return "File don't have extension";
}
}
Converts InputStream to a String
/**
* Converts InputStream to a String
* @param in
* @return
* @throws IOException
*/
public static String convertInputStreamToString(final InputStream in ) throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = in .read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString(StandardCharsets.UTF_8.name());
}
/**
* Converts InputStream to a String
* @param in
* @return
* @throws IOException
*/
public static String convertInputStreamToString(final InputStream in ) throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = in .read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString(StandardCharsets.UTF_8.name());
}
Reads the content of a file to a String
/**
* Reads content of a file to a String
* @param path
* @return
* @throws IOException
*/
public String readFileAsString(Path path) throws IOException {
return new String(Files.readAllBytes(path));
}
/**
* Reads content of a file to a String
* @param path
* @return
* @throws IOException
*/
public String readFileAsString(Path path) throws IOException {
return new String(Files.readAllBytes(path));
}
Get the current working directory path
/**
* Get current working directory path
* @return
*/
public static String getCurrentWorkingDirectoryPath() {
return FileSystems.getDefault().getPath("").toAbsolutePath().toString();
}
/**
* Get current working directory path
* @return
*/
public static String getCurrentWorkingDirectoryPath() {
return FileSystems.getDefault().getPath("").toAbsolutePath().toString();
}
Returns the value of java.io.tmpdir system property. It appends separator if not present at the end.
/**
* Returns the value of java.io.tmpdir system property.
* It appends separator if not present at the end.
* @return
*/
public static String tmpDirName() {
String tmpDirName = System.getProperty("java.io.tmpdir");
if (!tmpDirName.endsWith(File.separator)) {
tmpDirName += File.separator;
}
return tmpDirName;
}
/**
* Returns the value of java.io.tmpdir system property.
* It appends separator if not present at the end.
* @return
*/
public static String tmpDirName() {
String tmpDirName = System.getProperty("java.io.tmpdir");
if (!tmpDirName.endsWith(File.separator)) {
tmpDirName += File.separator;
}
return tmpDirName;
}
Returns the path to the system temporary directory
/**
* Returns the path to the system temporary directory.
*
* @return the path to the system temporary directory.
*/
public static String getTempDirectoryPath() {
return System.getProperty("java.io.tmpdir");
}
/**
* Returns the path to the system temporary directory.
*
* @return the path to the system temporary directory.
*/
public static String getTempDirectoryPath() {
return System.getProperty("java.io.tmpdir");
}
Returns the path to the user's home directory
/**
* Returns the path to the user's home directory.
*
* @return the path to the user's home directory.
*
*/
public static String getUserDirectoryPath() {
return System.getProperty("user.home");
}
/**
* Returns the path to the user's home directory.
*
* @return the path to the user's home directory.
*
*/
public static String getUserDirectoryPath() {
return System.getProperty("user.home");
}
Gets the extension of a file name, like ".png" or ".jpg".
/**
* Gets the extension of a file name, like ".png" or ".jpg".
*
* @param uri
* @return Extension including the dot("."); "" if there is no extension;
* null if uri was null.
*/
public static String getExtension(String uri) {
if (uri == null) {
return null;
}
int dot = uri.lastIndexOf(".");
if (dot >= 0) {
return uri.substring(dot);
} else {
// No extension.
return "";
}
}
/**
* Gets the extension of a file name, like ".png" or ".jpg".
*
* @param uri
* @return Extension including the dot("."); "" if there is no extension;
* null if uri was null.
*/
public static String getExtension(String uri) {
if (uri == null) {
return null;
}
int dot = uri.lastIndexOf(".");
if (dot >= 0) {
return uri.substring(dot);
} else {
// No extension.
return "";
}
}
Compares the contents of two files to determine if they are equal or not
/**
* Compares the contents of two files to determine if they are equal or not.
* <p>
* This method checks to see if the two files are different lengths
* or if they point to the same file, before resorting to byte-by-byte
* comparison of the contents.
* <p>
* Code origin: Avalon
*
* @param file1 the first file
* @param file2 the second file
* @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 {
final boolean file1Exists = file1.exists();
if (file1Exists != file2.exists()) {
return false;
}
if (!file1Exists) {
// two not existing files are equal
return true;
}
if (file1.isDirectory() || file2.isDirectory()) {
// don't want to compare directory contents
throw new IOException("Can't compare directories, only files");
}
if (file1.length() != file2.length()) {
// lengths differ, cannot be equal
return false;
}
if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) {
// same file
return true;
}
try (InputStream input1 = new FileInputStream(file1); InputStream input2 = new FileInputStream(file2)) {
return IOUtils.contentEquals(input1, input2);
}
}
/**
* Compares the contents of two files to determine if they are equal or not.
* <p>
* This method checks to see if the two files are different lengths
* or if they point to the same file, before resorting to byte-by-byte
* comparison of the contents.
* <p>
* Code origin: Avalon
*
* @param file1 the first file
* @param file2 the second file
* @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 {
final boolean file1Exists = file1.exists();
if (file1Exists != file2.exists()) {
return false;
}
if (!file1Exists) {
// two not existing files are equal
return true;
}
if (file1.isDirectory() || file2.isDirectory()) {
// don't want to compare directory contents
throw new IOException("Can't compare directories, only files");
}
if (file1.length() != file2.length()) {
// lengths differ, cannot be equal
return false;
}
if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) {
// same file
return true;
}
try (InputStream input1 = new FileInputStream(file1); InputStream input2 = new FileInputStream(file2)) {
return IOUtils.contentEquals(input1, input2);
}
}
Get the path only without the file name
**
*
Returns the path only(without file name).*
*
@param file *
@return *
/
public static File getPathWithoutFilename(File file) {
if (file != null) {
if (file.isDirectory()) {
// no file to be split off. Return everything
return file;
} else {
String filename = file.getName();
String filepath = file.getAbsolutePath();
// Construct path without file name.
String pathwithoutname = filepath.substring(0,
filepath.length() - filename.length());
if (pathwithoutname.endsWith("/")) {
pathwithoutname = pathwithoutname.substring(0, pathwithoutname.length() - 1);
}
return new File(pathwithoutname);
}
}
return null;
}
**
*
Returns the path only(without file name).*
*
@param file *
@return *
/
public static File getPathWithoutFilename(File file) {
if (file != null) {
if (file.isDirectory()) {
// no file to be split off. Return everything
return file;
} else {
String filename = file.getName();
String filepath = file.getAbsolutePath();
// Construct path without file name.
String pathwithoutname = filepath.substring(0,
filepath.length() - filename.length());
if (pathwithoutname.endsWith("/")) {
pathwithoutname = pathwithoutname.substring(0, pathwithoutname.length() - 1);
}
return new File(pathwithoutname);
}
}
return null;
}
Tests if the specified File is newer than the specified Date
public static boolean isFileNewer(final File file, final Date date) {
if (date == null) {
throw new IllegalArgumentException("No specified date");
}
return isFileNewer(file, date.getTime());
}
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;
}
public static boolean isFileNewer(final File file, final Date date) {
if (date == null) {
throw new IllegalArgumentException("No specified date");
}
return isFileNewer(file, date.getTime());
}
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;
}
Join file and extension
/**
* Join file and extension
* @param file
* @param ext
* @return
*/
public static String join(String file, String ext) {
return file + '/' + ext;
}
/**
* Join file and extension
* @param file
* @param ext
* @return
*/
public static String join(String file, String ext) {
return file + '/' + ext;
}
Check if a directory exists
/**
* Check if a directory existss
*
* @param dir
* the directory to check
* @return {@code true} if the {@code dir} exists on the file system
*/
public static boolean exists(String dir) {
l.debug("Checking existence of directory [" + dir + "]");
File f = new File(dir);
if (f.exists()) {
l.debug("[" + dir + "] exists.");
return true;
}
l.debug("[" + dir + "] does not exist.");
return false;
}
/**
* Check if a directory existss
*
* @param dir
* the directory to check
* @return {@code true} if the {@code dir} exists on the file system
*/
public static boolean exists(String dir) {
l.debug("Checking existence of directory [" + dir + "]");
File f = new File(dir);
if (f.exists()) {
l.debug("[" + dir + "] exists.");
return true;
}
l.debug("[" + dir + "] does not exist.");
return false;
}
Move file from source to destination
/**
* A wrapper for {@link java.io.File#renameTo(File)}
*
* @param oldf
* the original filename
* @param newf
* the new filename
* @return {@code true} if the move was successful
*/
public static boolean move(File oldf, File newf) {
return oldf.renameTo(newf);
}
/**
* A wrapper for {@link java.io.File#renameTo(File)}
*
* @param oldf
* the original filename
* @param newf
* the new filename
* @return {@code true} if the move was successful
*/
public static boolean move(File oldf, File newf) {
return oldf.renameTo(newf);
}
Create a directory if does not exist
/**
* Creates {@code dir} if it doesn't yet exist. A wrapper for
* {@link java.io.File#mkdir()}
*
* @param dir
* the directory to create
* @return {@code true} if the operation was successful
*/
public static boolean mkdir(String dir) {
boolean success = exists(dir) ? true : new File(dir).mkdir();
return success;
}
/**
* Creates {@code dir} if it doesn't yet exist. A wrapper for
* {@link java.io.File#mkdir()}
*
* @param dir
* the directory to create
* @return {@code true} if the operation was successful
*/
public static boolean mkdir(String dir) {
boolean success = exists(dir) ? true : new File(dir).mkdir();
return success;
}
Create all the directories in the path if does not exist
/**
* Creates all {@code dir}s in the path as needed. A wrapper for
* {@link java.io.File#mkdirs()}
*
* @param dir
* the path to create
* @return {@code true} if the operation was successful
*/
public static boolean mkdirs(String dir) {
boolean success = exists(dir) ? true : new File(dir).mkdirs();
return success;
}
/**
* Creates all {@code dir}s in the path as needed. A wrapper for
* {@link java.io.File#mkdirs()}
*
* @param dir
* the path to create
* @return {@code true} if the operation was successful
*/
public static boolean mkdirs(String dir) {
boolean success = exists(dir) ? true : new File(dir).mkdirs();
return success;
}
Recursively deletes the path and all its content and returns true if it succeeds
/**
* recursively deletes the path and all it's content and returns true if it succeeds
* Note that the content could be partially deleted and the method return false
*
* @param path the path to delete
* @return true if the path was deleted
*/
public static boolean forceDeletePath(File path) {
if (path == null) {
return false;
}
if (path.exists() && path.isDirectory()) {
File[] files = path.listFiles();
for (File file: files) {
if (file.isDirectory()) {
forceDeletePath(file);
} else {
file.delete();
}
}
}
return path.delete();
}
/**
* recursively deletes the path and all it's content and returns true if it succeeds
* Note that the content could be partially deleted and the method return false
*
* @param path the path to delete
* @return true if the path was deleted
*/
public static boolean forceDeletePath(File path) {
if (path == null) {
return false;
}
if (path.exists() && path.isDirectory()) {
File[] files = path.listFiles();
for (File file: files) {
if (file.isDirectory()) {
forceDeletePath(file);
} else {
file.delete();
}
}
}
return path.delete();
}
Gets a recursive list of directory content files
/**
* Gets a recursive list of directory contents
*
* @param d
* the directory to interrogate
* @param depth
* the number of level to recurse
* @return a list of directory contents
*/
public static List < File > getFileList(File d, int depth) {
List < File > fList = new ArrayList < > ();
l.debug("checking [" + d.getName() + "]");
if (d.canRead() && d.isDirectory()) {
File[] list = d.listFiles();
for (int i = 0; i < list.length; i++) {
File f = list[i];
if (f.isFile()) {
fList.add(f);
l.debug("Adding [" + f.getName() + "]");
} else {
if (depth > 0) {
l.debug("Descending...");
fList.addAll(getFileList(f, depth - 1));
} else if (depth == -1) {
fList.addAll(getFileList(f, -1));
}
}
}
}
return fList;
}
Do comment if you have any other useful file utility methods, which will help everyone to use.
Learn Java IO in depth on Java IO Tutorial
/**
* Gets a recursive list of directory contents
*
* @param d
* the directory to interrogate
* @param depth
* the number of level to recurse
* @return a list of directory contents
*/
public static List < File > getFileList(File d, int depth) {
List < File > fList = new ArrayList < > ();
l.debug("checking [" + d.getName() + "]");
if (d.canRead() && d.isDirectory()) {
File[] list = d.listFiles();
for (int i = 0; i < list.length; i++) {
File f = list[i];
if (f.isFile()) {
fList.add(f);
l.debug("Adding [" + f.getName() + "]");
} else {
if (depth > 0) {
l.debug("Descending...");
fList.addAll(getFileList(f, depth - 1));
} else if (depth == -1) {
fList.addAll(getFileList(f, -1));
}
}
}
}
return fList;
}
Learn Java IO in depth on Java IO Tutorial
Comments
Post a Comment
Leave Comment