Class IOUtil
- java.lang.Object
-
- com.jalios.io.IOUtil
-
public class IOUtil extends java.lang.Object
This class provides a set of static methods which perform various i/o operations.- Author:
- Olivier Dedieu
-
-
Field Summary
Fields Modifier and Type Field Description static int
DOWNLOAD_ERROR
static int
DOWNLOAD_OK
static java.lang.String
MIMETYPE_PLAINTEXT
protected static org.apache.oro.text.regex.Pattern
patternBlank1
protected static org.apache.oro.text.regex.Pattern
patternBlank2
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static java.lang.String
base64DecodeAndInflateString(java.lang.String str)
Inflates Base64 encoded string.static boolean
belongsToDirectory(java.io.File dir, java.io.File untrustedFile)
Check that the specified file belongs to the specified directory or any of its subdirectory.static boolean
canWrite(java.io.File file, boolean checkParent)
Tests whether the application can modify to the file denoted by the given file.static boolean
checkFileSizeAndMtime(java.io.File file, long size, long mtime)
Returns true if the given file exists and has the given size and the given mtime.static void
closeQuietly(java.io.Closeable closeable)
Close the given Closeable.static void
closeQuietly(java.io.InputStream inputStream)
Close the given InputStream.static void
closeQuietly(java.io.OutputStream outputStream)
Close the given OutputStream.static void
closeQuietly(java.io.Reader reader)
Close the given reader.static void
closeQuietly(java.io.Writer writer)
Close the given Writer.static void
convertCharset(java.io.File file, java.lang.String fromCS, java.lang.String toCS)
Encode the given file with a given charset.static int
copy(java.io.InputStream input, java.io.OutputStream output)
Copy bytes from anInputStream
to anOutputStream
.static void
copy(java.io.InputStream input, java.io.Writer output, java.lang.String encoding)
Copy bytes from anInputStream
to chars on aWriter
using the specified character encoding, or UTF-8 if null.static void
copy(java.io.Reader input, java.io.OutputStream output, java.lang.String encoding)
Copy chars from aReader
to bytes on anOutputStream
using the specified character encoding, and calling flush.static int
copy(java.io.Reader input, java.io.Writer output)
Copy chars from aReader
to aWriter
.static void
copyFile(java.io.File f1, java.io.File f2)
Copy f1 into f2 (mkdirs for f2)static void
copyFile(java.lang.String filename1, java.lang.String filename2)
Copy filename1 into filename2 (mkdirs for filename2)static java.io.File
createTempDir()
Creates a new empty directorystatic java.io.File
createTempDir(java.lang.String name, java.lang.String prefix, java.io.File parentDir, boolean clear)
Creates a new empty directorystatic void
deepCopy(java.io.File srcDir, java.io.File tgtDir)
Perform a directory deep copy.static void
deepCopy(java.io.File srcDir, java.io.File tgtDir, boolean deleteEmptyFile)
Perform a directory deep copy.static void
deepCopy(java.io.File srcDir, java.io.File tgtDir, boolean deleteEmptyFile, java.io.FileFilter filter)
Perform a directory deep copy.static void
deepDelete(java.io.File file)
Deletes a whole directory.static void
deepDelete(java.io.File file, ActionListener listener)
Deletes a whole directory.static void
deepDeleteEmptyDirectories(java.io.File dir)
Delete recursively all enpty directories under a given directory.static void
deepDeleteEmptyDirectories(java.io.File dir, java.io.FileFilter filter)
Delete recursively all enpty directories under a given directory.static void
deepDeleteEmptyDirectories(java.io.File dir, java.io.FileFilter filter, ActionListener listener)
Delete recursively all enpty directories under a given directory.static java.util.List<java.io.File>
deepListFiles(java.io.File dir, java.io.FileFilter filter)
Return a list of files from the given directory and matching the given filter.static java.util.List<java.io.File>
deepListFiles(java.io.File dir, java.io.FileFilter filter, boolean checkDir)
Return a list of files from the given directory and matching the given filter.static void
deepListFiles(java.io.File file, java.util.Set<java.io.File> fileSet, java.util.Set<java.lang.String> blackSet)
Follow recursively a Path each File that are not Blacklisted (ends with a String of the BlackListSet) are added to the FileSet Compare (convert \\ to /) but store File with \ or / depends of platformstatic java.lang.String
deflateAndBase64EncodeString(java.lang.String str)
Compresses (deflates) a string and Base64 encodes the result and returns it as a string.static int
downloadFile(java.net.URL url, java.io.File file, long lastModified, java.lang.String ticket)
Download the given URLstatic byte[]
emptyInputStream(java.io.DataInputStream dis)
Emptys an InputStreamstatic void
forceDeepCopy(java.io.File srcDir, java.io.File tgtDir, boolean deleteEmptyFile, java.io.FileFilter filter)
Perform a directory deep copy.static java.lang.String
getDownloadTicket(java.io.File file)
Get a download ticket for the given filestatic java.lang.String
getExtension(java.io.File file)
Returns the extension of the given file (without the leading "." char).static java.lang.String
getExtension(java.lang.String filename)
Returns the extension of the given file (without the leading "." char).static java.io.InputStream
getInputStream(java.net.HttpURLConnection httpConn)
Retrieve the input stream of the specified HttpURLConnection, decoded appropriately if gzip was used.static java.lang.String
getMimeTypeFromMagicNumber(java.io.File file)
Gives the mime type of a file.static java.lang.String
getNewDirectory(java.io.File baseDir, java.lang.String subDir, long maxFilesPerDir)
Returns the relative path of directory to use for the new document to be created.static java.lang.String
getQualifiedName(java.io.File file)
Returns the name of a given file, without its extension.static java.lang.String
getQualifiedName(java.lang.String filename)
Returns the name of a given file, without its extension.static java.lang.String
getRelativePath(java.io.File dir, java.io.File file)
Return the relative path of the specified file in the specified directory.static java.io.File
getTempDir()
static java.io.File
getTempDir(java.lang.String name, java.lang.String prefix, java.io.File parentDir)
Returns An abstract pathname denoting an empty directory (this directory is not created).static java.io.InputStream
getZipFileStream(java.lang.String fileName, java.io.File zipFile)
Returns an InputStream on the File representing by the given fileName in the given zip file.static java.io.InputStream
getZipFileStream(java.lang.String fileName, java.io.File zipFile, boolean regexp)
static boolean
goToLine(java.io.InputStream in, long line)
Move the position of the given InputStream to the given line.static boolean
goToLine(java.io.RandomAccessFile raf, long line)
Move the position of the given InputStream to the given line.static boolean
isParent(java.io.File parent, java.io.File child)
Check if a File is a child of an other File recursively.static boolean
isSameContent(java.io.File f1, java.io.File f2)
Returns true if the given files have the same content.static boolean
moveFile(java.io.File f1, java.io.File f2)
Move f1 into f2 (mkdirs for f2).static java.net.HttpURLConnection
openConnection(java.net.URL url, boolean doOutput, boolean doInput, java.lang.String method)
Open a new HttpURLConnection for the specified urlstatic java.lang.String[]
readList(java.io.Reader reader)
Returns all the lines read on a given Reader.static void
removeBlankLines(java.lang.String filename, boolean trim)
Remove all blank lines of a file.static void
searchAndReplace(java.io.File file, java.lang.String[] search, java.lang.String[] replace)
Execute an array of regular expression on a given file content.static void
searchAndReplace(java.io.File file, java.util.Map<java.lang.String,java.lang.String> map)
Execute a map of regular expression on a given file content.static java.lang.String
substringFile(java.io.File parentFile, java.io.File childFile)
If Parent is parent of child then we return the substraction: childPath - parentPath.static java.lang.String[]
tail(java.io.File file, int size, boolean skipBlank, java.lang.String encoding)
Returns the last lines of a file.static java.io.File
translateFile(java.io.File file, java.io.File srcDir, java.io.File tgtDir)
Returns the translated path of a given file which belongs to a given source directory into a target directory.static void
unzip(java.io.File file, java.io.File dir)
Unzip a filestatic void
unzip(java.io.File file, java.io.File dir, java.io.FileFilter filter)
Unzip a filestatic void
unzip(java.io.File file, java.io.File dir, java.io.FileFilter filter, java.nio.charset.Charset charset)
Unzip a filestatic void
unzip(java.lang.String filename, java.lang.String tgtDirname)
Unzip a filestatic void
unzip(java.lang.String filename, java.lang.String tgtDirname, java.io.FileFilter filter)
Unzip a file Adapted from: Working with Java Archive APIs Lawrence Rodrigues Java Report On-line http://archive.javareport.com/9808/html/features/archive/9806/rodrigues.shtmlstatic void
unzip(java.lang.String filename, java.lang.String tgtDirname, java.io.FileFilter filter, java.nio.charset.Charset charset)
Unzip a file Adapted from: Working with Java Archive APIs Lawrence Rodrigues Java Report On-line http://archive.javareport.com/9808/html/features/archive/9806/rodrigues.shtmlstatic void
writeArray(java.io.Writer writer, java.lang.String[] array)
Writes an array of String on a given Writer.static void
writeEnumeration(java.io.Writer writer, java.util.Enumeration<?> enu)
Writes an enumeration of object on a given Writer.static void
writeIterator(java.io.Writer writer, java.util.Iterator<?> it)
Writes an iteration of object on a given Writer.static void
zip(java.io.File[] files, java.lang.String destFile, int[] prefixLength, java.io.FileFilter[] filters)
Zip an array of files or directories into a file.static void
zip(java.io.File file, java.lang.String zipFile, int prefixLength, java.io.FileFilter filter)
static java.lang.String
zip(java.lang.String filename, boolean isParentDirRemoved)
Zip a file or a whole directory.static void
zip(java.lang.String filename, java.lang.String zipFile, boolean isParentDirRemoved)
Zip a file or a whole directorystatic void
zipWriter(java.io.File file, java.util.zip.ZipOutputStream zos, int prefixLength, java.io.FileFilter filter)
Zip all files of a directory that are accepted by the given FileFilter.
-
-
-
Field Detail
-
DOWNLOAD_ERROR
public static int DOWNLOAD_ERROR
-
DOWNLOAD_OK
public static int DOWNLOAD_OK
-
patternBlank1
protected static org.apache.oro.text.regex.Pattern patternBlank1
-
patternBlank2
protected static org.apache.oro.text.regex.Pattern patternBlank2
-
MIMETYPE_PLAINTEXT
public static final java.lang.String MIMETYPE_PLAINTEXT
- See Also:
- Constant Field Values
-
-
Method Detail
-
readList
public static java.lang.String[] readList(java.io.Reader reader) throws java.io.IOException
Returns all the lines read on a given Reader. All the lines are trimmed. Blank line and line which starts with # are skipped.- Parameters:
reader
- the reader- Returns:
- an array of String.
- Throws:
java.io.IOException
- if an exception occurs
-
deepListFiles
public static void deepListFiles(java.io.File file, java.util.Set<java.io.File> fileSet, java.util.Set<java.lang.String> blackSet)
Follow recursively a Path each File that are not Blacklisted (ends with a String of the BlackListSet) are added to the FileSet Compare (convert \\ to /) but store File with \ or / depends of platform- Parameters:
file
- the directory to followfileSet
- a Set where to put all filesblackSet
- a Set of String to identify Files that ends with that String
-
deepListFiles
public static java.util.List<java.io.File> deepListFiles(java.io.File dir, java.io.FileFilter filter)
Return a list of files from the given directory and matching the given filter. If a filter is provided, the directories (and their content) that do not match the filter are skipped.- Parameters:
dir
- the directory to explorefilter
- the FileFilter to use (may be null)- Returns:
- a List of java.io.File
- Since:
- jcms-4.1
- See Also:
deepListFiles(File, FileFilter, boolean)
-
deepListFiles
public static java.util.List<java.io.File> deepListFiles(java.io.File dir, java.io.FileFilter filter, boolean checkDir)
Return a list of files from the given directory and matching the given filter.- Parameters:
dir
- the directory to explorefilter
- the FileFilter to use (may be null)checkDir
- if true the directories that do not match the filter are skipped.- Returns:
- a List of java.io.File
- Since:
- jcms-5.6.1
-
substringFile
public static java.lang.String substringFile(java.io.File parentFile, java.io.File childFile)
If Parent is parent of child then we return the substraction: childPath - parentPath. Else return full child path. WARNING: return / for unix and \ for windows- Parameters:
parentFile
- the parent FilechildFile
- the child File- Returns:
- childPath - parentPath
-
writeArray
public static void writeArray(java.io.Writer writer, java.lang.String[] array) throws java.io.IOException
Writes an array of String on a given Writer.- Parameters:
writer
- the writerarray
- the array of String to write- Throws:
java.io.IOException
- if an exception occurs
-
writeEnumeration
public static void writeEnumeration(java.io.Writer writer, java.util.Enumeration<?> enu) throws java.io.IOException
Writes an enumeration of object on a given Writer. Uses the toString() method.- Parameters:
writer
- the writerenu
- the enumeration- Throws:
java.io.IOException
- if an exception occurs
-
writeIterator
public static void writeIterator(java.io.Writer writer, java.util.Iterator<?> it) throws java.io.IOException
Writes an iteration of object on a given Writer. Uses the toString() method.- Parameters:
writer
- the writerit
- the iterator- Throws:
java.io.IOException
- if an exception occurs
-
unzip
public static void unzip(java.io.File file, java.io.File dir) throws java.io.IOException
Unzip a file- Parameters:
file
- the file to unzipdir
- the target directory- Throws:
java.io.IOException
- if an exception occurs- See Also:
unzip(String, String, FileFilter)
-
unzip
public static void unzip(java.io.File file, java.io.File dir, java.io.FileFilter filter) throws java.io.IOException
Unzip a file- Parameters:
file
- the file to unzipdir
- the target directoryfilter
- an optional FileFilter to filter the file to be extracted.- Throws:
java.io.IOException
- if an exception occurs- See Also:
unzip(String, String, FileFilter)
-
unzip
public static void unzip(java.lang.String filename, java.lang.String tgtDirname) throws java.io.IOException
Unzip a file- Parameters:
filename
- the name of the file to unziptgtDirname
- the name of the target directory- Throws:
java.io.IOException
- if an exception occurs- See Also:
unzip(String, String, FileFilter)
-
unzip
public static void unzip(java.lang.String filename, java.lang.String tgtDirname, java.io.FileFilter filter) throws java.io.IOException
Unzip a file Adapted from: Working with Java Archive APIs Lawrence Rodrigues Java Report On-line http://archive.javareport.com/9808/html/features/archive/9806/rodrigues.shtml- Parameters:
filename
- the name of the file to unziptgtDirname
- the name of the target directoryfilter
- an optional FileFilter to filter the file to be extracted.- Throws:
java.io.IOException
- if an exception occurs- Since:
- jcms-5.7.0
-
unzip
public static void unzip(java.io.File file, java.io.File dir, java.io.FileFilter filter, java.nio.charset.Charset charset) throws java.io.IOException
Unzip a file- Parameters:
file
- the file to unzipdir
- the target directoryfilter
- an optional FileFilter to filter the file to be extracted.charset
- The charset to be used to decode the ZIP entry name (ignored if the language encoding bit of the ZIP entry's general purpose bit flag is set).- Throws:
java.io.IOException
- if an exception occurs- Since:
- jcms-9.0.4
- See Also:
unzip(String, String, FileFilter)
-
unzip
public static void unzip(java.lang.String filename, java.lang.String tgtDirname, java.io.FileFilter filter, java.nio.charset.Charset charset) throws java.io.IOException
Unzip a file Adapted from: Working with Java Archive APIs Lawrence Rodrigues Java Report On-line http://archive.javareport.com/9808/html/features/archive/9806/rodrigues.shtml- Parameters:
filename
- the name of the file to unziptgtDirname
- the name of the target directoryfilter
- an optional FileFilter to filter the file to be extracted.charset
- The charset to be used to decode the ZIP entry name (ignored if the language encoding bit of the ZIP entry's general purpose bit flag is set). Since jcms-10.0.3 / JCMS-7402, theCp437
charset is used if none is specified (it is the most commonly used and compatible charset for zip file).- Throws:
java.io.IOException
- if an exception occurs- Since:
- jcms-9.0.4
-
zip
public static java.lang.String zip(java.lang.String filename, boolean isParentDirRemoved) throws java.io.IOException
Zip a file or a whole directory. It produces a zip file which has the same name + ".zip"- Parameters:
filename
- the name of file or directory to zipisParentDirRemoved
- true if the parent path prefix of the filename must be removed in the zip file (eg: foo/* instead of a/b/c/foo/* when zipping directory "a/b/c/foo/")- Returns:
- String the absolute path of the zip file
- Throws:
java.io.IOException
- if an exception occurs
-
zip
public static void zip(java.lang.String filename, java.lang.String zipFile, boolean isParentDirRemoved) throws java.io.IOException
Zip a file or a whole directory- Parameters:
filename
- the name of file or directory to zipzipFile
- the name of the zip file to produceisParentDirRemoved
- true if the parent path prefix of the filename must be removed in the zip file (eg: foo/* instead of a/b/c/foo/* when zipping directory "a/b/c/foo/")- Throws:
java.io.IOException
- if an exception occurs
-
zip
public static void zip(java.io.File file, java.lang.String zipFile, int prefixLength, java.io.FileFilter filter) throws java.io.IOException
- Throws:
java.io.IOException
-
zip
public static void zip(java.io.File[] files, java.lang.String destFile, int[] prefixLength, java.io.FileFilter[] filters) throws java.io.IOException
Zip an array of files or directories into a file. Files are filtered by an array of FileFilters and are named according to an array of prefix sizes.- Parameters:
files
- the array of files or directories to be zippeddestFile
- the path of the destination zip fileprefixLength
- an array of prefix size to be used for each element of the files array.filters
- array of FileFilters to be used for filtering files.- Throws:
java.io.IOException
- if an exception occurs
-
zipWriter
public static void zipWriter(java.io.File file, java.util.zip.ZipOutputStream zos, int prefixLength, java.io.FileFilter filter) throws java.io.IOException
Zip all files of a directory that are accepted by the given FileFilter.- Parameters:
file
- the file or directory to be zippedzos
- the ZipOutputStream into which the file has to be addedprefixLength
- the size of the prefixfilter
- the filter to be used- Throws:
java.io.IOException
- if an exception occurs
-
getZipFileStream
public static java.io.InputStream getZipFileStream(java.lang.String fileName, java.io.File zipFile)
Returns an InputStream on the File representing by the given fileName in the given zip file. Caller must close the Stream.- Parameters:
fileName
- the file name of the file to seekzipFile
- File reprenst the zip- Returns:
- InputStream an InputStream to the given file in the zip
-
getZipFileStream
public static java.io.InputStream getZipFileStream(java.lang.String fileName, java.io.File zipFile, boolean regexp)
-
deflateAndBase64EncodeString
public static java.lang.String deflateAndBase64EncodeString(java.lang.String str) throws java.io.IOException
Compresses (deflates) a string and Base64 encodes the result and returns it as a string.- Parameters:
str
- The string to compress and encode.- Returns:
- Compressed and Base64 encoded result.
- Throws:
java.io.IOException
- Will probably not happen, maybe if there is a bug in the code or we run out of memory.
-
base64DecodeAndInflateString
public static java.lang.String base64DecodeAndInflateString(java.lang.String str) throws java.util.zip.DataFormatException, java.io.UnsupportedEncodingException
Inflates Base64 encoded string. Basically the reverse of deflateAndBase64EncodeFileContents, except that it does not write to a file.- Parameters:
str
- String should be compressed and Base64 encoded data.- Returns:
- The original string (decoded and inflated(uncompressed)).
- Throws:
java.util.zip.DataFormatException
- on bad input.java.io.UnsupportedEncodingException
- if an exception occurs
-
deepDelete
public static void deepDelete(java.io.File file)
Deletes a whole directory. Use it with care !- Parameters:
file
- the directory to destroy
-
deepDelete
public static void deepDelete(java.io.File file, ActionListener listener)
Deletes a whole directory. Use it with care !- Parameters:
file
- the directory to destroylistener
- a custom ActionListener used to perform custom actino during recursive calls- Since:
- jcms5.7.3
-
deepDeleteEmptyDirectories
public static void deepDeleteEmptyDirectories(java.io.File dir)
Delete recursively all enpty directories under a given directory. THe given directory will also be deleted.- Parameters:
dir
- the directory to destroy
-
deepDeleteEmptyDirectories
public static void deepDeleteEmptyDirectories(java.io.File dir, java.io.FileFilter filter)
Delete recursively all enpty directories under a given directory. THe given directory will also be deleted.- Parameters:
dir
- the directory to destroyfilter
- files to ignore and remove
-
deepDeleteEmptyDirectories
public static void deepDeleteEmptyDirectories(java.io.File dir, java.io.FileFilter filter, ActionListener listener)
Delete recursively all enpty directories under a given directory. The given directory will also be deleted.- Parameters:
dir
- the directory to destroyfilter
- FileFilter used to find files to be deleted before checking whether the directory is emptylistener
- to perform action during recursive calls
-
translateFile
public static java.io.File translateFile(java.io.File file, java.io.File srcDir, java.io.File tgtDir)
Returns the translated path of a given file which belongs to a given source directory into a target directory. Example: translateFile(/a/b/c.txt, /a/, /x/y/) returns /x/y/b/c.txt- Parameters:
file
- the file to translatesrcDir
- the source directorytgtDir
- the target directory- Returns:
- the translated file
- Since:
- jcms-4.0.2
-
searchAndReplace
public static void searchAndReplace(java.io.File file, java.lang.String[] search, java.lang.String[] replace)
Execute an array of regular expression on a given file content. In this implementation search and replace arrays must fullfill String.replaceAll() requirement.- Parameters:
file
- the file to parsesearch
- an array of regular expression to matchreplace
- ann array of regular expression to replace
-
searchAndReplace
public static void searchAndReplace(java.io.File file, java.util.Map<java.lang.String,java.lang.String> map)
Execute a map of regular expression on a given file content. In this implementation search and replace arrays must fullfill String.replaceAll() requirement.- Parameters:
file
- the file to parsemap
- a map with regexp as key and substitute string as value.
-
deepCopy
public static void deepCopy(java.io.File srcDir, java.io.File tgtDir, boolean deleteEmptyFile, java.io.FileFilter filter) throws java.io.IOException
Perform a directory deep copy. If deleteEmptyFile is true, all the empty source files (length = 0) will be used as marker to delete the corresponding target files.- Parameters:
srcDir
- the source directory to copytgtDir
- the target directorydeleteEmptyFile
- if true delete empty files.filter
- the filter to be used (may be null)- Throws:
java.io.IOException
- if it append for one file.- Since:
- jcms-4.1.1
-
forceDeepCopy
public static void forceDeepCopy(java.io.File srcDir, java.io.File tgtDir, boolean deleteEmptyFile, java.io.FileFilter filter)
Perform a directory deep copy. If deleteEmptyFile is true, all the empty source files (length = 0) will be used as marker to delete the corresponding target files. The operation is performed for every file, even if an IOException has been thrown previously for a file.- Parameters:
srcDir
- the source directory to copytgtDir
- the target directorydeleteEmptyFile
- if true delete empty files.filter
- the filter to be used (may be null)- Since:
- jcms-5.7.4
-
deepCopy
public static void deepCopy(java.io.File srcDir, java.io.File tgtDir, boolean deleteEmptyFile) throws java.io.IOException
Perform a directory deep copy. If deleteEmptyFile is true, all the empty source files (length = 0) will be used as marker to delete the corresponding target files.- Parameters:
srcDir
- the source directory to copytgtDir
- the target directorydeleteEmptyFile
- if true delete empty files.- Throws:
java.io.IOException
- if an exception occurs- Since:
- jcms-4.0.2
-
deepCopy
public static void deepCopy(java.io.File srcDir, java.io.File tgtDir) throws java.io.IOException
Perform a directory deep copy.- Parameters:
srcDir
- the source directory to copytgtDir
- the target directory- Throws:
java.io.IOException
- if an exception occurs
-
isParent
public static boolean isParent(java.io.File parent, java.io.File child)
Check if a File is a child of an other File recursively.- Parameters:
parent
- the parent filechild
- the child file- Returns:
- boolean
-
copyFile
public static void copyFile(java.lang.String filename1, java.lang.String filename2) throws java.io.IOException
Copy filename1 into filename2 (mkdirs for filename2)- Parameters:
filename1
- the source filefilename2
- the target file- Throws:
java.io.IOException
- if an exception occurs
-
copyFile
public static void copyFile(java.io.File f1, java.io.File f2) throws java.io.IOException
Copy f1 into f2 (mkdirs for f2)- Parameters:
f1
- the source filef2
- the target file- Throws:
java.io.IOException
- if an exception occurs
-
moveFile
public static boolean moveFile(java.io.File f1, java.io.File f2)
Move f1 into f2 (mkdirs for f2). Try with renameTo. If it fails (may occurs on Windows on just created temp file), calls copyFile() and delete().- Parameters:
f1
- the source filef2
- the target file- Returns:
true
if and only if the moving succeeded;false
otherwise.- Since:
- jcms-4.0.2
-
emptyInputStream
public static byte[] emptyInputStream(java.io.DataInputStream dis)
Emptys an InputStream- Parameters:
dis
- the DataInputStream to empty- Returns:
- the array of byte read.
-
removeBlankLines
public static void removeBlankLines(java.lang.String filename, boolean trim) throws java.io.IOException
Remove all blank lines of a file. Uses UTF-8 encoding for reading and writing the file.- Parameters:
filename
- the name of the file from which to remove blank lines.trim
- If false, remove only blank lines without space (i.e. matching /^$/) otherwise remove blank lines and space lines (i.e. matching /^\s*$/).- Throws:
java.io.IOException
- if an exception occurs
-
getTempDir
public static java.io.File getTempDir()
- Returns:
- the path to the tmp directory
- Since:
- jcms-10.0.8
-
createTempDir
public static java.io.File createTempDir()
Creates a new empty directory- Returns:
- An abstract pathname denoting a newly-created empty directory
-
createTempDir
public static java.io.File createTempDir(java.lang.String name, java.lang.String prefix, java.io.File parentDir, boolean clear)
Creates a new empty directory- Parameters:
name
- The name of the directory to create. If null, generate a name based on prefix and current time.prefix
- The prefix string to be used in generating the file's nameparentDir
- The parent directory in which the directory is to be created, or null if the default temporary-file directory is to be usedclear
- if true and if this directory already exists the content is deep deleted- Returns:
- An abstract pathname denoting a newly-created empty directory
- Since:
- jcms-4.0.2
-
getTempDir
public static java.io.File getTempDir(java.lang.String name, java.lang.String prefix, java.io.File parentDir)
Returns An abstract pathname denoting an empty directory (this directory is not created).- Parameters:
name
- The name of the directory to create. If null, generate a name.prefix
- The prefix string to be used in generating the file's nameparentDir
- The parent directory in which the directory is to be created, or null if the default temporary-file directory is to be used- Returns:
- An abstract pathname denoting an empty directory
- Since:
- jcms-4.0.2
-
canWrite
public static boolean canWrite(java.io.File file, boolean checkParent)
Tests whether the application can modify to the file denoted by the given file. If file does not exists and checkParent is true, the test is extended to the parent (recursively).- Parameters:
file
- the file to testcheckParent
- true if the parent must checked- Returns:
- true if this file can be write
- Since:
- jcms-4.0.2
-
getRelativePath
public static java.lang.String getRelativePath(java.io.File dir, java.io.File file)
Return the relative path of the specified file in the specified directory.The returned path is platform independent :
- "/" is used as file separator.
- characters are encoded or escaped according to specification indicated in java class
URI
.
Examples :
IOUtil.getRelativePath(new File("/foo/"), new File("/foo/bar/out.txt")); => "bar/out.txt" IOUtil.getRelativePath(new File("c:\\foo"), new File("c:\\foo\\bar\\out.txt")); => "bar/out.txt" IOUtil.getRelativePath(new File("/dir1/"), new File("/dir2/file.txt")); => null IOUtil.getRelativePath(new File("/foo/"), new File("/foo/bar baz/out.txt")); => "bar%20baz/out.txt"
- Parameters:
dir
- the directoryfile
- the file- Returns:
- the relative path or null if no relative path can be computed.
- Since:
- jcms-4.1
-
belongsToDirectory
public static boolean belongsToDirectory(java.io.File dir, java.io.File untrustedFile)
Check that the specified file belongs to the specified directory or any of its subdirectory.Exemple :
File dir = new File("/some/directory/"); File fileOk = new File("/some/directory/subdirectory/ok.txt"); File fileKo = new File("/etc/passwd"); assertTrue(IOUtil.belongsToDirectory(dir, fileOk)); assertFalse(IOUtil.belongsToDirectory(dir, fileKo));
- Parameters:
dir
- the directoryuntrustedFile
- the file to check- Returns:
- true if the file is part of the directory, false otherwise
- Throws:
java.lang.IllegalArgumentException
- if any of the parameter is null- Since:
- jcms-7.1
-
goToLine
public static boolean goToLine(java.io.InputStream in, long line) throws java.io.IOException
Move the position of the given InputStream to the given line.- Parameters:
in
- the InputStream to move the position.line
- the line to be reached- Returns:
- true if the line has been reached, false otherwite (line out of file size)
- Throws:
java.io.IOException
- if an exception occurs- Since:
- jcms-5.0.1
-
goToLine
public static boolean goToLine(java.io.RandomAccessFile raf, long line) throws java.io.IOException
Move the position of the given InputStream to the given line.- Parameters:
raf
- the RandomAccessFile to move the position.line
- the line to be reached- Returns:
- true if the line has been reached, false otherwite (line out of file size)
- Throws:
java.io.IOException
- if an exception occurs- Since:
- jcms-5.0.1
-
getExtension
public static java.lang.String getExtension(java.io.File file)
Returns the extension of the given file (without the leading "." char).Extension is always returned in lowercase (since JCMS-2732 / jcms-7.0.3).
Examples:foo/bar.XML
returnsxml
.Extension is accepted only if it contains exclusivel alpha numeric characters "a-zA-Z0-9" (since JCMS-8976 / jcms-10.0.6).
Examples:foo/bar. zig
orfoo/bar. éxt
returns empty string.
The regular expression defining the accepted extension can be override using system propertycom.jalios.io.IOUtil.EXTENSION_AUTHORIZED_PATTERN
- Parameters:
file
- the file to get the extension- Returns:
- the extension of the given file (in lowercase) or the empty string if no valid extension could be identified
- Since:
- jcms-5.5.0
-
getExtension
public static java.lang.String getExtension(java.lang.String filename)
Returns the extension of the given file (without the leading "." char).Extension is always returned in lowercase (since JCMS-2732 / jcms-7.0.3).
Example:foo/bar.XML
returnsxml
.Extension is accepted only if it contains exclusivel alpha numeric characters "a-zA-Z0-9" (since JCMS-8976 / jcms-10.0.6).
Examples:foo/bar. zig
orfoo/bar. éxt
returns empty string.
The regular expression defining the accepted extension can be override using system propertycom.jalios.io.IOUtil.EXTENSION_AUTHORIZED_PATTERN
- Parameters:
filename
- the filename to get the extension- Returns:
- the extension of the given filename
- Since:
- jcms-5.5.0
- See Also:
getExtension(File)
-
getQualifiedName
public static java.lang.String getQualifiedName(java.io.File file)
Returns the name of a given file, without its extension.Examples :
FileName.Ext
returnsFileName
File.Name.ext
returnsFile.Name
FileName
returnsFileName
path/to/FileName
returnsFileName
Dot-files are returned entirely (since JCMS-2732 / jcms-7.0.3).
Example:.bashrc
returns.bashrc
.Files with invalid extension (see
getExtension(File)
) are returned entirely (since JCMS-8976 / jcms-10.0.6)
Examples:foo/bar. zig
returnsbar. zig
,foo/bar. éxt
returnsbar. éxt
- Parameters:
file
- the File of which to retrieve qualified name- Returns:
- String the qualified name of the given File
- Since:
- jcms-5.5.0
-
getQualifiedName
public static java.lang.String getQualifiedName(java.lang.String filename)
Returns the name of a given file, without its extension.Examples :
FileName.Ext
returnsFileName
File.Name.ext
returnsFile.Name
FileName
returnsFileName
path/to/FileName
returnsFileName
Dot-files are returned entirely (since JCMS-2732 / jcms-7.0.3).
Example:.bashrc
returns.bashrc
.Files with invalid extension (see
getExtension(File)
) are returned entirely (since JCMS-8976 / jcms-10.0.6)
Examples:foo/bar. zig
returnsbar. zig
,foo/bar. éxt
returnsbar. éxt
- Parameters:
filename
- the file name- Returns:
- String the qualified name of the given File
- Since:
- jcms-5.5.0
- See Also:
getQualifiedName(File)
-
convertCharset
public static void convertCharset(java.io.File file, java.lang.String fromCS, java.lang.String toCS) throws java.io.IOException
Encode the given file with a given charset.- Parameters:
file
- the file to be encodedfromCS
- the original charset of the filetoCS
- the new charset of the file- Throws:
java.io.IOException
- if an exception occurs- Since:
- jcms-5.5.0
-
copy
public static int copy(java.io.InputStream input, java.io.OutputStream output) throws java.io.IOException
Copy bytes from anInputStream
to anOutputStream
.This method buffers the input internally, so there is no need to use a
BufferedInputStream
.- Parameters:
input
- theInputStream
to read fromoutput
- theOutputStream
to write to- Returns:
- the number of bytes copied
- Throws:
java.lang.NullPointerException
- if the input or output is nulljava.io.IOException
- if an I/O error occurs- Since:
- jcms-5.5.0
-
copy
public static void copy(java.io.InputStream input, java.io.Writer output, java.lang.String encoding) throws java.io.IOException
Copy bytes from anInputStream
to chars on aWriter
using the specified character encoding, or UTF-8 if null.This method buffers the input internally, so there is no need to use a
BufferedInputStream
.Character encoding names can be found at IANA.
This method uses
InputStreamReader
.- Parameters:
input
- theInputStream
to read fromoutput
- theWriter
to write toencoding
- the encoding to use, null means platform default- Throws:
java.lang.NullPointerException
- if the input or output is nulljava.io.IOException
- if an I/O error occurs- Since:
- jcms-5.5.0
-
copy
public static int copy(java.io.Reader input, java.io.Writer output) throws java.io.IOException
Copy chars from aReader
to aWriter
.This method buffers the input internally, so there is no need to use a
BufferedReader
.- Parameters:
input
- theReader
to read fromoutput
- theWriter
to write to- Returns:
- the number of characters copied
- Throws:
java.lang.NullPointerException
- if the input or output is nulljava.io.IOException
- if an I/O error occurs- Since:
- jcms-5.5.0
-
copy
public static void copy(java.io.Reader input, java.io.OutputStream output, java.lang.String encoding) throws java.io.IOException
Copy chars from aReader
to bytes on anOutputStream
using the specified character encoding, and calling flush.This method buffers the input internally, so there is no need to use a
BufferedReader
.Character encoding names can be found at IANA.
Due to the implementation of OutputStreamWriter, this method performs a flush.
This method uses
OutputStreamWriter
.- Parameters:
input
- theReader
to read fromoutput
- theOutputStream
to write toencoding
- the encoding to use, null means platform default- Throws:
java.lang.NullPointerException
- if the input or output is nulljava.io.IOException
- if an I/O error occurs- Since:
- jcms-5.5.0
-
closeQuietly
public static void closeQuietly(java.io.Reader reader)
Close the given reader. This convenient method is typically used in a finally block.- Parameters:
reader
- the Reader.- Since:
- jcms-5.6.0
-
closeQuietly
public static void closeQuietly(java.io.Writer writer)
Close the given Writer. This convenient method is intended to be used in a finally block.- Parameters:
writer
- the Writer.- Since:
- jcms-5.6.0
-
closeQuietly
public static void closeQuietly(java.io.InputStream inputStream)
Close the given InputStream. This convenient method is intended to be used in a finally block.- Parameters:
inputStream
- the InputStream.- Since:
- jcms-5.6.0
-
closeQuietly
public static void closeQuietly(java.io.OutputStream outputStream)
Close the given OutputStream. This convenient method is intended to be used in a finally block.- Parameters:
outputStream
- the OutputStream.- Since:
- jcms-5.6.0
-
closeQuietly
public static void closeQuietly(java.io.Closeable closeable)
Close the given Closeable. This convenient method is intended to be used in a finally block.- Parameters:
closeable
- the Closeable.- Since:
- jcms-10.0.1
-
isSameContent
public static boolean isSameContent(java.io.File f1, java.io.File f2)
Returns true if the given files have the same content.- Parameters:
f1
- the first file to be comparedf2
- the second file to be compared- Returns:
- true if the two files have the same content.
- Since:
- jcms-5.7.0
-
getNewDirectory
public static java.lang.String getNewDirectory(java.io.File baseDir, java.lang.String subDir, long maxFilesPerDir)
Returns the relative path of directory to use for the new document to be created. The directories are created.- Parameters:
baseDir
- the base directory (eg /usr/local/tomcat/webapps/jcms/)subDir
- an optional sub directory, may be null (eg upload/docs/image/gif/)maxFilesPerDir
- how many files are allowed per directory.- Returns:
- String the directory path, relative to the webapp, with the trailing slash ("/"). e.g: upload/docs/image/gif/2006/11/
- Since:
- jcms-5.7.0
-
tail
public static java.lang.String[] tail(java.io.File file, int size, boolean skipBlank, java.lang.String encoding) throws java.io.IOException
Returns the last lines of a file.- Parameters:
file
- the filesize
- how many lines to returnsskipBlank
- if true skip the blank linesencoding
- the file encoding- Returns:
- the last lines of a file.
- Throws:
java.io.IOException
- if an exception occurs- Since:
- jcms-5.7.2
-
getDownloadTicket
public static java.lang.String getDownloadTicket(java.io.File file)
Get a download ticket for the given file- Parameters:
file
- the file to get a ticket for- Returns:
- a String containing the ticket
- Since:
- jcms-4.1
-
downloadFile
public static int downloadFile(java.net.URL url, java.io.File file, long lastModified, java.lang.String ticket)
Download the given URL- Parameters:
url
- the URL to downloadfile
- the target filelastModified
- if > 0, the last lastModified date of the file will be set to this valueticket
- the ticket to be used for the download- Returns:
- the status code
- Since:
- jcms-4.1
-
openConnection
public static java.net.HttpURLConnection openConnection(java.net.URL url, boolean doOutput, boolean doInput, java.lang.String method) throws java.io.IOException
Open a new HttpURLConnection for the specified url- Parameters:
url
- the URL for which HttpURLConnection is openeddoOutput
- seeURLConnection.setDoOutput(boolean)
doInput
- seeURLConnection.setDoInput(boolean)
method
- seeHttpURLConnection.setRequestMethod(String)
- Returns:
- a new instance of HttpURLConnection
- Throws:
java.io.IOException
- if an exception occurs- Since:
- jcms-4.1
-
getInputStream
public static java.io.InputStream getInputStream(java.net.HttpURLConnection httpConn) throws java.io.IOException
Retrieve the input stream of the specified HttpURLConnection, decoded appropriately if gzip was used.- Parameters:
httpConn
- the HttpUrlConnection being used- Returns:
- a input stream
- Throws:
java.io.IOException
- if an exception occurs- Since:
- jcms-4.1
-
checkFileSizeAndMtime
public static boolean checkFileSizeAndMtime(java.io.File file, long size, long mtime)
Returns true if the given file exists and has the given size and the given mtime.- Parameters:
file
- the filesize
- the excepted sizemtime
- the expected mtime- Returns:
- true if the given file exists and has the given size and the given mtime.
- Since:
- jcms-5.7.2
-
getMimeTypeFromMagicNumber
public static java.lang.String getMimeTypeFromMagicNumber(java.io.File file)
Gives the mime type of a file. Licence concern : This method is based upon Aperture MagicMimeTypeIdentifier. The code was modified at the margin to be compatible with JRE 1.4.2. Given the licence of Aperture : Open Software Licence (OSL), this modified code of Aperture classes are held at the disposal on demand at support@jalios.com Concerned classes :UtfUtil
MagicNumber
MagicMimeTypeIdentifier
MagicString
MagicNumber
- Parameters:
file
- the file to test- Returns:
- the mime type of the file or null if not found
- Since:
- JCMS-5.7.3
-
-