public class Files extends Object
FileNotFoundException
. Please note that in all cases target content is overwritten.
Finally, there are method working with temporary files as target. These methods return newly created temporary file and is caller responsibility to remove it when is not longer necessary. This library does not keep record of created temporary file and there is no attempt to remove then, not even at virtual machine exit.
This utility class allows for sub-classing. See js.util
for utility sub-classing description.
Modifier and Type | Class and Description |
---|---|
static class |
Files.FileNotify
File notification types used by
inotify(java.io.File, FileNotify, int) utility method. |
Modifier and Type | Field and Description |
---|---|
private static int |
BUFFER_SIZE
The size of buffer used by copy operations.
|
static String |
CURRENT_DIR
Current directory file name.
|
private static Pattern |
DOT_PATTERN
Regular expression pattern for dot (.) character.
|
static char |
EXTENSION_SEPARATOR
The extension separator character.
|
private static List<String> |
IMAGE_FILE_EXTENSIONS
Standard extensions for image files.
|
private static Map<Files.FileNotify,Predicate> |
INOTIFY_PREDICATES
Predefined predicates used by
inotify(File, FileNotify, int) . |
static String |
LINE_SEPARATOR
System dependent line separator used to separate text lines into character streams.
|
private static Log |
log
Class logger.
|
private static String |
PARTIAL_FILE_SUFFIX
Partially transfered file name for
download(URL, File) . |
private static String |
SEPARATOR_CHAR_REX
Regular expression for path separator.
|
private static String |
TMP_FILE_EXTENSION
Extension for temporary files.
|
private static String |
TMP_FILE_PREFIX
Prefix for temporary files.
|
private static char |
UNIX_SEPARATOR
The Unix separator character.
|
private static String |
URL_PATH_SEPARATOR
URL path separator.
|
private static char |
WINDOWS_SEPARATOR
The Windows separator character.
|
Modifier | Constructor and Description |
---|---|
protected |
Files()
Prevent default constructor synthesis but allow sub-classing.
|
Modifier and Type | Method and Description |
---|---|
static String |
basename(File file)
Return file name without extension.
|
static String |
basename(String path)
Return base name for given file path.
|
static void |
close(Closeable closeable)
Close given
closeable if not null but ignoring IO exception generated by failing close operation. |
static long |
copy(File source,
File target)
Copy source file to target.
|
static long |
copy(File file,
OutputStream outputStream)
Copy source file bytes to requested output stream.
|
static File |
copy(InputStream stream)
Binary copy to temporary file.
|
static long |
copy(InputStream inputStream,
File file)
Copy bytes from requested input stream to given target file.
|
static long |
copy(InputStream inputStream,
File baseDir,
String fileName)
Copy bytes from given input stream to file denoted by requested base directory and file name.
|
static long |
copy(InputStream inputStream,
OutputStream outputStream)
Copy bytes from input to given output stream then close both byte streams.
|
static File |
copy(InputStream stream,
String encoding)
Copy text from byte stream using specified encoding to temporary file then close both input stream and temporary
file.
|
static File |
copy(Reader reader)
Copy text from character stream to temporary file then close both the source reader and temporary file.
|
static int |
copy(Reader reader,
Writer writer)
Copy characters from a reader to a given writer then close both character streams.
|
static File |
copy(URL url)
Binary copy from URL to local temporary file.
|
static long |
copy(URL url,
File file)
Copy bytes from remote file denoted by given URL to specified local file.
|
static long |
copy(URL url,
File baseDir,
String fileName)
Copy remote binary file denoted by requested URL to local file identified by given base directory and file name.
|
static long |
copy(URL url,
OutputStream outputStream)
Copy bytes from remote file denoted by given URL to requested output stream.
|
static File |
copy(URL url,
String encoding)
Copy text from URL using specified encoding to local temporary file then close both URL input stream and temporary
file.
|
static BufferedReader |
createBufferedReader(InputStream stream)
Create buffered reader from bytes stream using UTF-8 charset.
|
static BufferedWriter |
createBufferedWriter(OutputStream stream)
Create buffered writer from bytes stream using UTF-8 charset.
|
private static File |
createTempFile()
Create temporary file using library specific prefix and extension.
|
static void |
delete(File file)
Delete file if exists throwing exception if delete fails.
|
static String |
dot2path(String qualifiedName)
Replace all dots from given qualified name with platform specific path separator.
|
static String |
dot2path(String qualifiedName,
String fileExtension)
Convert qualified name to platform specific path and add given extension.
|
static String |
dot2urlpath(String qualifiedName)
Same as
dot2path(String) but always uses forward slash as path separator, as used by URLs. |
static void |
download(URL url,
File file)
Atomic download file from specified URL to local target file.
|
static void |
dump(InputStream inputStream)
Dump byte input stream content to standard output till end of input stream.
|
static void |
dump(Reader reader)
Dump UTF-8 character stream content to standard out.
|
static String |
getExtension(File file)
Get file extension as lower case or empty string.
|
static String |
getExtension(String path)
Get the lower case extension of the file denoted by given path or empty string if not extension.
|
static String |
getExtension(URL url)
Get extension of the file denoted by given URL or empty string if not extension.
|
static byte[] |
getFileDigest(File file)
Create MD5 message digest for requested file content.
|
static byte[] |
getFileDigest(InputStream inputStream)
Create MD5 message digest for bytes produced by given input stream till its end.
|
static List<String> |
getPathComponents(File file)
Get file path components.
|
static String |
getRelativePath(File baseDir,
File file,
boolean... forceURLPath)
Get file access path relative to a base directory.
|
static boolean |
inotify(File file,
Files.FileNotify notify,
int timeout)
Wait for requested action to happen on given file.
|
static boolean |
isImage(File file)
Guess if file is an image file based on file extension.
|
static boolean |
isImage(String extension)
Convenient alternative for
isImage(File) method. |
static File |
mkdirs(File file)
Create all ancestor directories for a requested file path.
|
static boolean |
move(String sourcePath,
String targetPath)
Move source file to requested destination but do not overwrite.
|
static String |
normalizePath(String path)
Ensure that path separators are compatible with current operating system.
|
static String |
path2dot(String path)
Convert a file path to a dot separated list of words.
|
static String |
path2unix(File file)
Convert a file to an Unix like path string.
|
static String |
path2unix(String path)
Convert file path to an Unix like path string.
|
private static void |
removeDirectory(File directory)
Utility method invoked recursively to remove directory files.
|
static File |
removeExtension(File file)
Remove extension from given file and create a new one with resulting path.
|
static String |
removeExtension(String path)
Remove extension from given file path and return resulting path.
|
static File |
removeFilesHierarchy(File baseDir)
Remove ALL files and directories from a given base directory.
|
static void |
renameTo(File source,
File destination)
Thin wrapper for
File.renameTo(File) throwing exception on fail. |
static File |
replaceExtension(File file,
String newExtension)
Replace extension on given file and return resulting file.
|
static String |
replaceExtension(String path,
String newExtension)
Replace extension on given file path and return resulting path.
|
private static Log log
public static final String CURRENT_DIR
public static final String LINE_SEPARATOR
private static final int BUFFER_SIZE
private static final String PARTIAL_FILE_SUFFIX
download(URL, File)
.private static final String SEPARATOR_CHAR_REX
private static final Pattern DOT_PATTERN
private static final String URL_PATH_SEPARATOR
public static final char EXTENSION_SEPARATOR
private static final char UNIX_SEPARATOR
private static final char WINDOWS_SEPARATOR
private static final String TMP_FILE_PREFIX
private static final String TMP_FILE_EXTENSION
private static final List<String> IMAGE_FILE_EXTENSIONS
isImage(File)
.private static final Map<Files.FileNotify,Predicate> INOTIFY_PREDICATES
inotify(File, FileNotify, int)
.protected Files()
public static BufferedReader createBufferedReader(InputStream stream)
file.encoding
is not the standard way to set default charset and to use host settings.stream
- input stream.public static BufferedWriter createBufferedWriter(OutputStream stream)
file.encoding
is not the standard way to set default charset and to use host settings.stream
- input stream.public static File copy(URL url) throws IOException, IllegalArgumentException
url
- source file URL.IOException
- if copy operation fails.IllegalArgumentException
- if url
parameter is null.public static File copy(InputStream stream) throws IOException
stream
- source stream.IOException
- if copy operation fails.public static File copy(URL url, String encoding) throws IOException, IllegalArgumentException
url
- source file URL,encoding
- character encoding to use.IOException
- if copy operation fails.IllegalArgumentException
- if url
parameter is null.public static File copy(InputStream stream, String encoding) throws IOException
stream
- input stream to read from,encoding
- used character encoding.IOException
- if copy operation fails.public static File copy(Reader reader) throws IOException
reader
- source character reader.IOException
- if copy operation fails.public static long copy(File source, File target) throws FileNotFoundException, IOException
source
- file to read from, should exist,target
- file to write to.FileNotFoundException
- if source file does not exist or target file does not exist and cannot be created.IOException
- if copy operation fails, including if target
is a directory.public static int copy(Reader reader, Writer writer) throws IOException
reader
- character stream to read from,writer
- character stream to write to.IOException
- if read or write operation fails.IllegalArgumentException
- if reader or writer is null.public static long copy(URL url, File baseDir, String fileName) throws FileNotFoundException, IOException, IllegalArgumentException
File.File(File, String)
. This method creates local file if it does already exist.url
- remote file URL,baseDir
- local file base directory,fileName
- local file name.FileNotFoundException
- if given local file does not exist and cannot be created.IOException
- if transfer fails.IllegalArgumentException
- if url
is null.public static long copy(InputStream inputStream, File baseDir, String fileName) throws FileNotFoundException, IOException
File.File(File, String)
. This method tries to create destination file and throws exception if
fails.inputStream
- source bytes stream,baseDir
- destination base directory,fileName
- destination file name.FileNotFoundException
- if given baseDir
and fileName
does not denote and existing
file and cannot be created.IOException
- if bytes transfer fails.public static long copy(InputStream inputStream, File file) throws FileNotFoundException, IOException
inputStream
- source input stream,file
- target file.FileNotFoundException
- if given file
does not exist and cannot be created.IOException
- if bytes transfer fails.public static long copy(URL url, File file) throws FileNotFoundException, IOException
url
- source remote file URL,file
- target local file.FileNotFoundException
- if given file
does not exist and cannot be created.IOException
- if bytes transfer fails.public static long copy(URL url, OutputStream outputStream) throws IOException, IllegalArgumentException
url
- URL of the source remote file,outputStream
- destination output stream.IOException
- the number of bytes transfered.IllegalArgumentException
- if url
is null.public static long copy(File file, OutputStream outputStream) throws IOException
file
- source file,outputStream
- destination output stream.FileNotFoundException
- if file
does not exist.IOException
- bytes processing fails.IllegalArgumentException
- if input file or output stream is null.public static long copy(InputStream inputStream, OutputStream outputStream) throws IOException, IllegalArgumentException
inputStream
- bytes input stream,outputStream
- bytes output stream.IOException
- if reading or writing fails.IllegalArgumentException
- if input or output stream is null or ZIP stream.public static void download(URL url, File file) throws IOException
url
- source file URL,file
- local target file.IOException
- if transfer or local write fails.public static void dump(InputStream inputStream) throws IOException
inputStream
- source byte input stream.IOException
- if reading from input stream fails.public static void dump(Reader reader) throws IOException
reader
- source UTF-8 character stream.IOException
- if reading from character stream fails.public static void close(Closeable closeable)
closeable
if not null but ignoring IO exception generated by failing close operation.
Please note that this helper method does not throw IOException
if close operation fails but still record
the event to error logger.closeable
- closeable to close.public static void renameTo(File source, File destination) throws IOException
File.renameTo(File)
throwing exception on fail. This method ensures destination file
parent directories exist. If destination file already exist its content is silently overwritten.
Warning: if destination file exists, it is overwritten and its old content lost.
source
- source file,destination
- destination file.IOException
- if rename operation fails.public static boolean move(String sourcePath, String targetPath) throws IllegalArgumentException
sourcePath
- source file path,targetPath
- target file path.IllegalArgumentException
- if source or target path parameter is null.public static String getRelativePath(File baseDir, File file, boolean... forceURLPath)
Resulting relative path uses system separator unless optional forceURLPath is supplied and is false; in this case always use /, no matter platform running JVM.
Known limitations: this method always assume that both base directory and file are on the same root; failing to satisfy this condition render not predictable results.
baseDir
- base directory,file
- file or directory to compute relative path,forceURLPath
- flag to force resulting path as URL path, i.e. always uses '/' for path components separator.IllegalArgumentException
- if any argument is null or empty.public static List<String> getPathComponents(File file)
file
- file to retrieve path components.public static String removeExtension(String path) throws IllegalArgumentException
path
- file path to remove extension from.IllegalArgumentException
- if path
parameter is null.public static File removeExtension(File file) throws IllegalArgumentException
file
- file to remove extension from.IllegalArgumentException
- if file
parameter is null.public static String replaceExtension(String path, String newExtension) throws IllegalArgumentException
path
- file path to replace extension,newExtension
- newly extension, with optional dot separator prefix.IllegalArgumentException
- if path or new extension parameter is null.public static File replaceExtension(File file, String newExtension) throws IllegalArgumentException
file
- file to replace extension,newExtension
- newly extension.IllegalArgumentException
- if file parameter is null.public static String path2dot(String path)
path
parameter is
null.path
- file path to convert.public static String path2unix(File file)
path2unix(String)
. Returns null if
file
parameter is null.file
- file to convert.public static String path2unix(String path)
path
is Windows like replaces drive letter
with Unix path root and all Windows path separators to Unix counterpart.
D:\\temp\file.txt -> /temp/file.txtIf
path
is already Unix like this method leave it as it is but remove trailing path separator, if any.
Returns null if path
parameter is null.path
- path to convert, trailing path separator ignored.public static String dot2path(String qualifiedName)
js.net.Transaction -> js/net/Transaction or js\net\TransactionReturns null if
qualifiedName
parameter is null.qualifiedName
- qualified name.public static String dot2urlpath(String qualifiedName)
dot2path(String)
but always uses forward slash as path separator, as used by URLs. Returns null if
qualifiedName
parameter is null.qualifiedName
- qualified name.public static String dot2path(String qualifiedName, String fileExtension)
dot2path(String)
to convert
qualifiedName
to file path then add give fileExtension
. Is legal for
fileExtension
to start with dot.
js.net.Transaction java -> js/net/Transaction.java or js\net\Transaction.java js.net.Transaction .java -> js/net/Transaction.java or js\net\Transaction.javaReturns null if
qualifiedName
parameter is null. If fileExtension
parameter is null
resulting path has no extension.qualifiedName
- qualified name,fileExtension
- requested file extension, leading dot accepted.public static String getExtension(URL url)
htm
not .htm
. Returns null if url
parameter
is null.url
- the URL of file to return extension.url
parameter is null.public static String getExtension(File file)
htm
not .htm
. Returns null if file
parameter is null.file
- file to return extension of.file
parameter is null.public static String getExtension(String path)
htm
not .htm
. Returns null if given
path
parameter is null.path
- the path of the file to return extension of.public static String basename(File file)
file
parameter is null.file
- file to return base name for.public static String basename(String path)
path
- file path string.private static File createTempFile() throws IOException
IOException
- if file creation fails.public static boolean isImage(File file)
file
- file to test.public static boolean isImage(String extension)
isImage(File)
method.extension
- file extension to test.public static byte[] getFileDigest(File file) throws FileNotFoundException, IOException
file
- file to create message digest for.FileNotFoundException
- if file
does not exist.IOException
- if file read operation fails.public static byte[] getFileDigest(InputStream inputStream) throws IOException
inputStream
- input stream for source bytes.IOException
- if file read operation fails.public static File mkdirs(File file) throws IOException, IllegalArgumentException
file
is assumed to be a file path,
not a directory; this method retrieve file parent and enact File.mkdirs()
. If given file reside into file
system root this method does nothing.
For caller convenience this method returns file
argument, see sample usage.
save(text, new FileWriter(Files.mkdirs(file)));
file
- file path.IOException
- if directories creation fails.IllegalArgumentException
- if file
parameter is null.public static void delete(File file) throws IOException
file
- file path.IOException
- if delete operation fails.IllegalArgumentException
- if file
parameter is null.public static File removeFilesHierarchy(File baseDir) throws IllegalArgumentException, IOException
baseDir
but directory itself is not removed. As a result baseDir
becomes
empty, that is, no children. If exception occur base directory state is not defined, that is, some files may be
removed and other may still be there.
For caller convenience this method returns given base directory. This allows to chain this method with
File.delete()
method, like Files.removeFilesHierarchy(dir).delete();
.
baseDir
- existing, not null, base directory to clean-up.File.delete()
.IllegalArgumentException
- if base directory argument is null or is not an existing directory.IOException
- if remove operation fails.private static void removeDirectory(File directory) throws IOException
directory
files
and remove them, one by one. If a child file is happen to be a directory this method invoked itself with child
directory as parameter. After child directory is clean-up iteration continue removing child directory itself. Note
that given directory
is not removed.
On remove exception directory
state is not defined, that is, some files may be removed while others
may not.
directory
- directory to remove files from.IOException
- if remove operation fails.public static boolean inotify(File file, Files.FileNotify notify, int timeout) throws IllegalArgumentException
timeout
is zero or negative this method returns
false immediately.
This implementation is a fallback solution for JVM without java.nio.file.WatchService
. Please consider
using watch service when available.
file
- file to wait for its state change,notify
- notify type,timeout
- timeout value.IllegalArgumentException
- if file
is null.Copyright © 2020. All rights reserved.