public class

IO

extends Object
java.lang.Object
   ↳ com.pnfsoftware.jeb.util.io.IO

Class Overview

File manipulation routines.

Summary

Public Constructors
IO()
Public Methods
static boolean compareFiles(File file0, File file1)
Compare the contents of two files for equality.
static boolean compressFolder(String folderPath, String zipfilePath)
Compress a folder and its contents to a zip archive.
static Thread copyAsync(InputStream input, OutputStream output)
Copy a continuous stream of data from a source to a destination.
static void copyFile(File src, File dst, boolean overwrite)
Copy a source file to a destination.
static long copyStream(InputStream input, OutputStream output)
Read bytes from an input stream and dump them to an output stream.@return
static long copyStream(InputStream input, OutputStream output, byte[] buffer)
Read bytes from an input stream and dump them to an output stream.@return
static boolean createDirectory(String path)
Create a directory.
static boolean createDirectory(File f)
Create a directory.
static boolean createFile(File file, boolean createDirs)
Create an empty file.
static void createFoldersForFile(File file)
Create the directory structure needed to store a file.
static File createTempFile(String exactname)
Create a file in the default temp folder.@return
static File createTempFile()
Create a file in the default temp folder.
static File createTempFolder(String folderName)
Create a directory in the default temporary-file directory.
static boolean deleteDirectory(File dir)
Delete a directory and its contents recursively.
static boolean deleteDirectory(String path)
Delete a directory and its contents recursively.
static boolean deleteDirectoryContents(File dir)
Delete a directory contents recursively (ie, clear the directory).
static void deleteDirectoryOnExit(File dir)
Delete a folder and all its contents recursively, when the virtual machine terminates.
static boolean deleteFile(File file)
Delete a file.
static String escapeFileName(String filename)
Escape filename invalid characters with an underscore.
static String escapeFileName(String filename, char newChar)
Escape illegal characters in filename by the provided char.
static String escapeFileNameStrict(String filename, char newChar)
Create a valid filename from any string.
static String escapeFileNameStrict(String filename)
Create a valid filename with an underscore for non alphanumeric char, '-', '_', '.' nor '''.
static String expandPath(String path)
Perform expansion of certain shell artifacts used in path names.
static void extractToFolder(File inputZipFile, File outputFolder)
Extract the contents of a zip archive to a target folder.
static String getCwd()
Get the path of the current working directory.
static String getExtension(String path)
static String getExtension(File file)
static byte getFirstByte(String path)
Get the first byte of a file.
static int getFirstIntLE(String path)
Get the first 4-byte of a file, read as a little-endian integer.
static short getFirstShortLE(String path)
Get the first 2-byte of a file, read as a little-endian short.
static File getParentFile2(File file)
A safer implementation of getParentFile().
static String getRelativePath(File file, File base)
Provide the path to a file relative to a base.
static File getTempFolder()
Retrieve the temporary folder.
static boolean isFile(String path)
Determine if a path refers to an existing file.
static List<File> listFiles(String folderpath)
Recursively do a directory listing.
static List<File> listFiles(File folder)
Recursively do a directory listing.
static String noExtension(String path)
static File noExtension(File file)
static List<String> parsePathElements(String s)
Parse the elements of a path.
static byte[] readFile(String path)
Read the contents of a binary file.@return
static byte[] readFile(File file, long maxAllowedSize)
Read the contents of a binary file.@return
static byte[] readFile(File file)
Read the contents of a binary files.@return
static byte[] readFileSafe(File file)
Read a binary file safely.
static String readInputLineSafe()
Read a line from the standard input.
static byte[] readInputStream(InputStream in)
Read and reliably return all bytes of an input stream.
static List<String> readLines(InputStream input)
Read the contents of a stream as a text buffer of UTF-8 encoded strings.@return
static List<String> readLines(File file)
Read the UTF-8 encoded lines of a text file.@return
static List<String> readLines(File file, Charset encoding)
Read the lines of a text file.@return
static List<String> readLines(InputStream input, Charset encoding)
Read the contents of a stream as a line of strings.
static List<String> readLinesSafe(File file, Charset encoding)
Read the lines of a text file.
static List<String> readLinesSafe(File file)
Read the lines of a UTF8 encoded text file.
static boolean renameFile(File src, File dst, int mode)
Rename a file with options.
static File replaceExtension(File file, String extension)
static String sanitizePath(String path, boolean isSinglePathElement, boolean replaceBlankCharacters)
Sanitize a path.
static String sanitizePathUnsafe(String path)
Attempt to sanitize a path.
static String setCwd(String cwd)
Set the path of the current working directory.
static void writeFile(File file, String str)
Write a string to a file using the default character encoding of the current system.
static void writeFile(File file, byte[] data, boolean createDirs)
Write data to a file whose containing directory structure may not exist.
static void writeFile(File file, byte[] data, int offset, int size)
Write data to a file.
static void writeFile(File file, String str, String charsetName)
Write a string to a file using the given character encoding of the current system.
static void writeFile(File file, byte[] data, int offset, int size, boolean createDirs)
Write data to a file whose containing directory structure may not exist.
static void writeFile(File file, byte[] data)
Write data to a file.
static boolean writeFileSafe(File file, byte[] data, int offset, int size, boolean createDirs)
Write a binary file safely.
static boolean writeFileSafe(File file, byte[] data, boolean createDirs)
Write a binary file safely.
static void writeLines(OutputStream output, List<? extends CharSequence> lines)
Write UTF-8 encoded strings.
static void writeLines(File file, List<? extends CharSequence> lines)
Write UTF-8 encoded strings.
static void writeLines(OutputStream output, List<? extends CharSequence> lines, Charset encoding)
Write strings.
static void writeLines(File file, List<? extends CharSequence> lines, Charset encoding)
Write strings.
static boolean writeLinesSafe(OutputStream output, List<? extends CharSequence> lines)
Write UTF-8 encoded strings.
static boolean writeLinesSafe(File file, List<? extends CharSequence> lines, Charset encoding)
Write strings.
static boolean writeLinesSafe(OutputStream output, List<? extends CharSequence> lines, Charset encoding)
Write strings.
static boolean writeLinesSafe(File file, List<? extends CharSequence> lines)
Write UTF-8 encoded strings.
[Expand]
Inherited Methods
From class java.lang.Object

Public Constructors

public IO ()

Public Methods

public static boolean compareFiles (File file0, File file1)

Compare the contents of two files for equality.

Parameters
file0 first file
file1 second file
Throws
FileNotFoundException one of the input file is not found
IOException other IO exception

public static boolean compressFolder (String folderPath, String zipfilePath)

Compress a folder and its contents to a zip archive.

Parameters
folderPath input folder
zipfilePath output zip file path
Returns
  • true on success

public static Thread copyAsync (InputStream input, OutputStream output)

Copy a continuous stream of data from a source to a destination. This method is non-blocking.

Parameters
input the source input stream
output the destination output stream
Returns
  • the daemon worker thread in charge of copying the data

public static void copyFile (File src, File dst, boolean overwrite)

Copy a source file to a destination.

Parameters
src source file (not a directory)
dst destination file or directory
overwrite if true, the destination file may be overwritten if it already exists
Throws
FileNotFoundException the source is not found
FileAlreadyExistsException the destination would be overwritten
IOException other IO exception

public static long copyStream (InputStream input, OutputStream output)

Read bytes from an input stream and dump them to an output stream.@return

Throws
IOException

public static long copyStream (InputStream input, OutputStream output, byte[] buffer)

Read bytes from an input stream and dump them to an output stream.@return

Parameters
buffer recommended use: multiple of 0x1000
Throws
IOException

public static boolean createDirectory (String path)

Create a directory.

Returns
  • true on success, else false

public static boolean createDirectory (File f)

Create a directory.

public static boolean createFile (File file, boolean createDirs)

Create an empty file.

Parameters
createDirs if true, the directory structure needed to contain the file will also be created
Returns
  • true if the named file does not exist and was successfully created; false if the named file already exists
Throws
IOException

public static void createFoldersForFile (File file)

Create the directory structure needed to store a file.

Throws
IOException

public static File createTempFile (String exactname)

Create a file in the default temp folder.@return

Throws
IOException

public static File createTempFile ()

Create a file in the default temp folder.

Returns
  • the file object
Throws
IOException on file creation error

public static File createTempFolder (String folderName)

Create a directory in the default temporary-file directory.

Parameters
folderName optional folder name; if null, a randomly named folder will be created
Returns
  • a File representing the newly created directory, or null on error
Throws
IOException if an IO exception happened

public static boolean deleteDirectory (File dir)

Delete a directory and its contents recursively.

Returns
  • true on success, false if errors were encountered; note that some files and directories may have been deleted

public static boolean deleteDirectory (String path)

Delete a directory and its contents recursively.

Returns
  • true on success

public static boolean deleteDirectoryContents (File dir)

Delete a directory contents recursively (ie, clear the directory). The directory itself is not deleted.

Returns
  • true on success, false if errors were encountered; note that some files and directories may have been deleted

public static void deleteDirectoryOnExit (File dir)

Delete a folder and all its contents recursively, when the virtual machine terminates.

Parameters
dir folder to be deleted

public static boolean deleteFile (File file)

Delete a file.

Parameters
file the file to be deleted
Returns
  • true on success

public static String escapeFileName (String filename)

Escape filename invalid characters with an underscore.

For proper path sanitization, use sanitizePath(String, boolean, boolean).

Parameters
filename to escape
Returns
  • the escaped filename

public static String escapeFileName (String filename, char newChar)

Escape illegal characters in filename by the provided char. Note than this is a black-list escaper (whitelist character would be too costly to manage any char) so file name can still be irrelevant on the target Operating System. The list of excluded characters are ':', '\', '/', '*', '"', '?', '|', '<', '>' which covers most of the invalid characters.

For proper path sanitization, use sanitizePath(String, boolean, boolean).

Parameters
filename to escape
newChar replacement character
Returns
  • the escaped filename

public static String escapeFileNameStrict (String filename, char newChar)

Create a valid filename from any string. Compared to escapeFileName(String, char), this is a white-list escaper so generated filename will be legal on any non-exotic target Operating System. The list of allowed characters are any alphanumeric char, '-', '_', '.', '''.

For proper path sanitization, use sanitizePath(String, boolean, boolean).

Parameters
filename to escape
newChar replacement character
Returns
  • the escaped filename

public static String escapeFileNameStrict (String filename)

Create a valid filename with an underscore for non alphanumeric char, '-', '_', '.' nor '''.

For proper path sanitization, use sanitizePath(String, boolean, boolean).

Parameters
filename to escape
Returns
  • the escaped filename

public static String expandPath (String path)

Perform expansion of certain shell artifacts used in path names.

Currently, the expansions performed are:

  • a leading tilda is expanded to a user's home directory

Returns
  • a full path name, if possible - otherwise, the original path is returned

public static void extractToFolder (File inputZipFile, File outputFolder)

Extract the contents of a zip archive to a target folder.

Parameters
inputZipFile input zip file path
outputFolder output folder directory
Throws
IOException if an error occurred; the current state of extraction within the target folder is not erased

public static String getCwd ()

Get the path of the current working directory.

public static String getExtension (String path)

public static String getExtension (File file)

public static byte getFirstByte (String path)

Get the first byte of a file. This method never throws exceptions. If an error occurs, 0 is returned. It is up to the client to handle that special case.

public static int getFirstIntLE (String path)

Get the first 4-byte of a file, read as a little-endian integer. This method never throws exceptions. If an error occurs, 0 is returned. It is up to the client to handle that special case.

Parameters
path file path
Returns
  • the first int, 0 on error

public static short getFirstShortLE (String path)

Get the first 2-byte of a file, read as a little-endian short. This method never throws exceptions. If an error occurs, 0 is returned. It is up to the client to handle that special case.

public static File getParentFile2 (File file)

A safer implementation of getParentFile(). If the input file is a single-level relative path (eg, "abc"), this method will first retrieve the absolute path (relative to the current folder) before trying to retrieve the parent folder.

Parameters
file file or folder
Returns
  • null if there is no parent folder, eg in the case of a a root folder

public static String getRelativePath (File file, File base)

Provide the path to a file relative to a base.

Parameters
file a file
base the base to check for
Returns
  • null if `file` is not rooted in `base`; else, the relative path of `file` (relative to `base`)
Throws
IOException other IO exception

public static File getTempFolder ()

Retrieve the temporary folder.

Returns
  • the temp folder, never null

public static boolean isFile (String path)

Determine if a path refers to an existing file.

public static List<File> listFiles (String folderpath)

Recursively do a directory listing. The list returned is a list of true files (not directories). Refer to the DirectoryEnumerator object for a more powerful file enumerator.

Returns
  • the list of absolute file paths

public static List<File> listFiles (File folder)

Recursively do a directory listing. The list returned is a list of true files (not directories). Refer to the DirectoryEnumerator object for a more powerful file enumerator.

Returns
  • the list of absolute files

public static String noExtension (String path)

public static File noExtension (File file)

public static List<String> parsePathElements (String s)

Parse the elements of a path.

Parameters
s a path
Returns
  • a list of path elements, possibly empty

public static byte[] readFile (String path)

Read the contents of a binary file.@return

Throws
IOException

public static byte[] readFile (File file, long maxAllowedSize)

Read the contents of a binary file.@return

Parameters
maxAllowedSize specify a maximum read size
Throws
IOException on IO error, or if the read size exceeds

public static byte[] readFile (File file)

Read the contents of a binary files.@return

Throws
IOException

public static byte[] readFileSafe (File file)

Read a binary file safely. If any error happens, an empty array is returned.

Parameters
file input file
Returns
  • the bytes in the file, never null (empty array on error)

public static String readInputLineSafe ()

Read a line from the standard input. This method is safe to use; it does not raise, instead returning a null string on error.

public static byte[] readInputStream (InputStream in)

Read and reliably return all bytes of an input stream. The stream must be less than 2Gb. The caller is responsible for closing the input stream after reading.@return

Throws
IOException

public static List<String> readLines (InputStream input)

Read the contents of a stream as a text buffer of UTF-8 encoded strings.@return

Throws
IOException

public static List<String> readLines (File file)

Read the UTF-8 encoded lines of a text file.@return

Throws
IOException

public static List<String> readLines (File file, Charset encoding)

Read the lines of a text file.@return

Throws
IOException

public static List<String> readLines (InputStream input, Charset encoding)

Read the contents of a stream as a line of strings.

Parameters
input the input stream
encoding the stream encoding
Returns
  • a list of strings, without new-line characters
Throws
IOException on IO error

public static List<String> readLinesSafe (File file, Charset encoding)

Read the lines of a text file. On error, the method returns null.

Returns
  • a list of lines without newline chars, null on error

public static List<String> readLinesSafe (File file)

Read the lines of a UTF8 encoded text file. On error, the method returns null.

Returns
  • a list of lines without newline chars, null on error

public static boolean renameFile (File src, File dst, int mode)

Rename a file with options.

Parameters
src source file
dst destination
mode define the mechanics of the renaming operations:
  • 0: standard rename, fail if 'dst' already exists or 'src' does not exist
  • 1: overwrite 'dst' if 'dst' already exists
  • 2: delete 'src' if 'dst' already exists
Returns
  • true on success

public static File replaceExtension (File file, String extension)

Parameters
extension the new extension, eg ".xyz"

public static String sanitizePath (String path, boolean isSinglePathElement, boolean replaceBlankCharacters)

Sanitize a path. The returned path is guaranteed to be legal on the current filesystem (FS) if and only if the element being sanitized is a single path element. For full paths elements, sanitization cannot be guaranteed because some characters which could yield to bad paths, cannot be safely sanitized.

Notes:
- the following characters are always sanitized: ? % * | < > "
- if a single path element is provided, the following characters are sanitized as well: / \ :

Parameters
path a path (absolute or not)
isSinglePathElement true if the provided path should be treated as a single path element, allowing more aggressive replacements
replaceBlankCharacters if true, sanitize all blank characters (per the Unicode definition of a blank character) as well, even though some may be legal
Returns
  • a sanitized path, never null, guaranteed to be valid on the current FS

public static String sanitizePathUnsafe (String path)

Attempt to sanitize a path.

Under some conditions, the returned path may be unsafe, eg on Windows: the sanitization of a path like "x::z" will generate an unsafe path. You must use sanitizePath(String, boolean, boolean) to guarantee sanitization.

public static String setCwd (String cwd)

Set the path of the current working directory.

Note: handle with care, changing the CWD may not impact all subsequent file read and write operations. It is safer to retrieve and use the CWD with getCwd().

Returns
  • previous working directory

public static void writeFile (File file, String str)

Write a string to a file using the default character encoding of the current system. Existing file contents will be overwritten.

Parameters
file destination file
str string
Throws
IOException on error

public static void writeFile (File file, byte[] data, boolean createDirs)

Write data to a file whose containing directory structure may not exist. Existing file contents will be overwritten.

Throws
IOException

public static void writeFile (File file, byte[] data, int offset, int size)

Write data to a file. Existing file contents will be overwritten.

Throws
IOException

public static void writeFile (File file, String str, String charsetName)

Write a string to a file using the given character encoding of the current system. Existing file contents will be overwritten.

Throws
IOException

public static void writeFile (File file, byte[] data, int offset, int size, boolean createDirs)

Write data to a file whose containing directory structure may not exist. Existing file contents will be overwritten.

Parameters
createDirs create the intermediate directories if need be
Throws
IOException

public static void writeFile (File file, byte[] data)

Write data to a file. Existing file contents will be overwritten.

Parameters
file destination file
data binary data to write
Throws
IOException on error

public static boolean writeFileSafe (File file, byte[] data, int offset, int size, boolean createDirs)

Write a binary file safely.

public static boolean writeFileSafe (File file, byte[] data, boolean createDirs)

Write a binary file safely.

public static void writeLines (OutputStream output, List<? extends CharSequence> lines)

Write UTF-8 encoded strings.

Throws
IOException

public static void writeLines (File file, List<? extends CharSequence> lines)

Write UTF-8 encoded strings.

Throws
IOException

public static void writeLines (OutputStream output, List<? extends CharSequence> lines, Charset encoding)

Write strings.

Throws
IOException

public static void writeLines (File file, List<? extends CharSequence> lines, Charset encoding)

Write strings.

Throws
IOException

public static boolean writeLinesSafe (OutputStream output, List<? extends CharSequence> lines)

Write UTF-8 encoded strings. On error, the method returns false.

public static boolean writeLinesSafe (File file, List<? extends CharSequence> lines, Charset encoding)

Write strings. On error, the method returns false.

public static boolean writeLinesSafe (OutputStream output, List<? extends CharSequence> lines, Charset encoding)

Write strings. On error, the method returns false.

public static boolean writeLinesSafe (File file, List<? extends CharSequence> lines)

Write UTF-8 encoded strings. On error, the method returns false.