Package org.gbif.utils.file
Class FileUtils
java.lang.Object
org.gbif.utils.file.FileUtils
Collection of file utils.
This class has only been tested for use with a UTF-8 system encoding.
This class has only been tested for use with a UTF-8 system encoding.
-
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic Stringclasspath2Filepath(String path) static InputStreamclasspathStream(String path) columnsToSet(InputStream source, int... column) columnsToSet(InputStream source, Set<String> resultSet, int... column) Reads a file and returns a unique set of multiple columns from lines which are no comments (starting with #) and trims whitespace.static voidcopyStreams(InputStream in, OutputStream out) static voidcopyStreamToFile(InputStream in, File out) static voidcreateParentDirs(File file) Creates any necessary but nonexistent parent directories of the specified file.static Filestatic FilecreateTempDir(String prefix, String suffix) static voiddeleteDirectoryRecursively(File directory) Delete directory recursively, including all its files, sub-folders, and sub-folder's files.static StringescapeFilename(String filename) Escapes a filename so it is a valid filename on all systems, replacing /.static FilegetClasspathFile(String path) static StringgetFileExtension(String fullName) Returns the file extension for the given file name, or the empty string if the file has no extension.static InputStreamgetInputStream(File source) static BufferedReadergetInputStreamReader(InputStream input) static BufferedReadergetInputStreamReader(InputStream input, String encoding) static org.apache.commons.io.LineIteratorgetLineIterator(InputStream source) static org.apache.commons.io.LineIteratorgetLineIterator(InputStream source, String encoding) intstatic BufferedReadergetUtf8Reader(File file) static StringhumanReadableByteCount(long bytes, boolean si) Converts the byte size into human-readable format.static booleanisCompressedFile(File source) voidmergeSortedFiles(List<File> sortFiles, Writer sortedFileWriter, Comparator<String> lineComparator) Merges a list of intermediary sort chunk files into a single sorted file.static ByteBufferreadByteBuffer(File file) Reads a complete file into a byte buffer.static ByteBufferreadByteBuffer(File file, int bufferSize) Reads the first bytes of a file into a byte buffer.static voidsetLinesPerMemorySort(int linesPerMemorySort) voidsort(File input, File sorted, String encoding, int column, String columnDelimiter, Character enclosedBy, String newlineDelimiter, int ignoreHeaderLines) Sorts the input file into the output file using the supplied delimited line parameters.voidsort(File input, File sorted, String encoding, int column, String columnDelimiter, Character enclosedBy, String newlineDelimiter, int ignoreHeaderLines, Comparator<String> lineComparator, boolean ignoreCase) Sorts the input file into the output file using the supplied delimited line parameters.voidsort(List<File> inputs, File sorted, String encoding, int column, String columnDelimiter, Character enclosedBy, String newlineDelimiter, int ignoreHeaderLines) Sorts the input file into the output file using the supplied delimited line parameters.voidsort(List<File> inputs, File sorted, String encoding, int column, String columnDelimiter, Character enclosedBy, String newlineDelimiter, int ignoreHeaderLines, Comparator<String> lineComparator, boolean ignoreCase) Sorts the input file into the output file using the supplied delimited line parameters.voidsortInJava(File input, File sorted, String encoding, Comparator<String> lineComparator, int ignoreHeaderLines) Sorts the input file into the output file using the supplied lineComparator.voidsortInJava(List<File> inputs, File sorted, String encoding, Comparator<String> lineComparator, int ignoreHeaderLines) Sorts the input file into the output file using the supplied lineComparator.Splits the supplied file into files of set line size and with a suffix.static WriterstartNewUtf8File(File file) static WriterstartNewUtf8XmlFile(File file) static LinkedList<String>streamToList(InputStream source) Takes a utf8 encoded input stream and reads in every line/row into a list.static LinkedList<String>streamToList(InputStream source, String encoding) streamToList(InputStream source, List<String> resultList) Reads a file and returns a list of all lines which are no comments (starting with #) and trims whitespace.streamToMap(InputStream source) Reads a utf8 encoded inut stream, splitsstreamToMap(InputStream source, int key, int value, boolean trimToNull) streamToMap(InputStream source, Map<String, String> result) Read a hashmap from a tab delimited utf8 input stream using the row number as an integer value and the entire row as the value.streamToMap(InputStream source, Map<String, String> result, int key, int value, boolean trimToNull) Read a hashmap from a tab delimited utf8 file, ignoring commented rows starting with #.streamToSet(InputStream source) streamToSet(InputStream source, Set<String> resultSet) Reads a file and returns a unique set of all lines which are no comments (starting with #) and trims whitespace.static StringtoFilePath(URL url) static voidCreates an empty file or updates the last updated timestamp on the same as the unix command of the same name.static File
-
Field Details
-
UTF8
-
TAB_DELIMITED
-
-
Constructor Details
-
FileUtils
public FileUtils()
-
-
Method Details
-
classpath2Filepath
-
classpathStream
- Throws:
IOException
-
columnsToSet
- Throws:
IOException
-
columnsToSet
public static Set<String> columnsToSet(InputStream source, Set<String> resultSet, int... column) throws IOException Reads a file and returns a unique set of multiple columns from lines which are no comments (starting with #) and trims whitespace.- Parameters:
source- the UTF-8 encoded text file with tab delimited columnsresultSet- the set implementation to be used. Will not be cleared before reading!column- variable length argument of column indices to process- Returns:
- set of column rows
- Throws:
IOException
-
copyStreams
- Throws:
IOException
-
copyStreamToFile
- Throws:
IOException
-
createTempDir
- Throws:
IOException
-
createTempDir
- Parameters:
prefix- The prefix string to be used in generating the file's name; must be at least three characters longsuffix- The suffix string to be used in generating the file's name; may be null, in which case the suffix ".tmp" will be used- Throws:
IOException
-
deleteDirectoryRecursively
Delete directory recursively, including all its files, sub-folders, and sub-folder's files.- Parameters:
directory- directory to delete recursively
-
escapeFilename
Escapes a filename so it is a valid filename on all systems, replacing /. .. \t\r\n.- Parameters:
filename- to be escaped
-
getClasspathFile
-
getInputStream
- Throws:
FileNotFoundException
-
getInputStreamReader
- Throws:
FileNotFoundException
-
getInputStreamReader
public static BufferedReader getInputStreamReader(InputStream input, String encoding) throws FileNotFoundException - Throws:
FileNotFoundException
-
getLineIterator
- Parameters:
source- the source input stream encoded in UTF-8
-
getLineIterator
public static org.apache.commons.io.LineIterator getLineIterator(InputStream source, String encoding) - Parameters:
source- the source input streamencoding- the encoding used by the input stream
-
getUtf8Reader
- Throws:
FileNotFoundException
-
humanReadableByteCount
Converts the byte size into human-readable format. Support both SI and byte format. -
isCompressedFile
-
readByteBuffer
Reads a complete file into a byte buffer.- Throws:
IOException
-
readByteBuffer
Reads the first bytes of a file into a byte buffer.- Parameters:
bufferSize- the number of bytes to read from the file- Throws:
IOException
-
setLinesPerMemorySort
- Parameters:
linesPerMemorySort- are the number of lines that should be sorted in memory, determining the number of file segments to be sorted when doing a Java file sort. Defaults to 100000, if you have memory available a higher value increases performance.
-
startNewUtf8File
- Throws:
IOException
-
startNewUtf8XmlFile
- Throws:
IOException
-
streamToList
Takes a utf8 encoded input stream and reads in every line/row into a list.- Returns:
- list of rows
- Throws:
IOException
-
streamToList
public static List<String> streamToList(InputStream source, List<String> resultList) throws IOException Reads a file and returns a list of all lines which are no comments (starting with #) and trims whitespace.- Parameters:
source- the UTF-8 encoded text file to readresultList- the list implementation to be used. Will not be cleared before reading!- Returns:
- list of lines
- Throws:
IOException
-
streamToList
public static LinkedList<String> streamToList(InputStream source, String encoding) throws IOException - Throws:
IOException
-
streamToMap
Reads a utf8 encoded inut stream, splits- Throws:
IOException
-
streamToMap
public static Map<String,String> streamToMap(InputStream source, int key, int value, boolean trimToNull) throws IOException - Throws:
IOException
-
streamToMap
public static Map<String,String> streamToMap(InputStream source, Map<String, String> result) throws IOExceptionRead a hashmap from a tab delimited utf8 input stream using the row number as an integer value and the entire row as the value. Ignores commented rows starting with #.- Parameters:
source- tab delimited text file to read- Throws:
IOException
-
streamToMap
public static Map<String,String> streamToMap(InputStream source, Map<String, String> result, int key, int value, boolean trimToNull) throws IOExceptionRead a hashmap from a tab delimited utf8 file, ignoring commented rows starting with #.- Parameters:
source- tab delimited input stream to readkey- column number to use as keyvalue- column number to use as valuetrimToNull- if true trims map entries to null- Throws:
IOException
-
streamToSet
- Throws:
IOException
-
streamToSet
Reads a file and returns a unique set of all lines which are no comments (starting with #) and trims whitespace.- Parameters:
source- the UTF-8 encoded text file to readresultSet- the set implementation to be used. Will not be cleared before reading!- Returns:
- set of unique lines
- Throws:
IOException
-
toFilePath
-
url2file
-
getLinesPerMemorySort
-
mergeSortedFiles
public void mergeSortedFiles(List<File> sortFiles, Writer sortedFileWriter, Comparator<String> lineComparator) throws IOException Merges a list of intermediary sort chunk files into a single sorted file. On completion, the intermediary sort chunk files are deleted.- Parameters:
sortFiles- sort chunk files to mergesortedFileWriter- writer to merge to. Can already be open and contain datalineComparator- To use when determining the order (reuse the one that was used to sort the individual files)- Throws:
IOException
-
sort
public void sort(File input, File sorted, String encoding, int column, String columnDelimiter, Character enclosedBy, String newlineDelimiter, int ignoreHeaderLines) throws IOException Sorts the input file into the output file using the supplied delimited line parameters. This method is not reliable when the sort field may contain Unicode codepoints outside the Basic Multilingual Plane, i.e. above . In that case, the sort order differs from Java's String sort order. This should not be a problem for most usage; the Supplementary Multilingual Planes contain ancient scripts, emojis, arrows and so on.- Parameters:
input- To sortsorted- The sorted version of the input excluding ignored header lines (see ignoreHeaderLines)column- the column that keeps the values to sort oncolumnDelimiter- the delimiter that separates columns in a rowenclosedBy- optional column enclosing character, e.g. a double quote for CSVsnewlineDelimiter- the chars used for new lines, usually \n, \n\r or \rignoreHeaderLines- number of beginning lines to ignore, e.g. headers- Throws:
IOException
-
sort
public void sort(List<File> inputs, File sorted, String encoding, int column, String columnDelimiter, Character enclosedBy, String newlineDelimiter, int ignoreHeaderLines) throws IOException Sorts the input file into the output file using the supplied delimited line parameters. This method is not reliable when the sort field may contain Unicode codepoints outside the Basic Multilingual Plane, i.e. above . In that case, the sort order differs from Java's String sort order. This should not be a problem for most usage; the Supplementary Multilingual Planes contain ancient scripts, emojis, arrows and so on.- Parameters:
inputs- To sortsorted- The sorted version of the input excluding ignored header lines (see ignoreHeaderLines)column- the column that keeps the values to sort oncolumnDelimiter- the delimiter that separates columns in a rowenclosedBy- optional column enclosing character, e.g. a double quote for CSVsnewlineDelimiter- the chars used for new lines, usually \n, \n\r or \rignoreHeaderLines- number of beginning lines to ignore, e.g. headers- Throws:
IOException
-
sort
public void sort(File input, File sorted, String encoding, int column, String columnDelimiter, Character enclosedBy, String newlineDelimiter, int ignoreHeaderLines, Comparator<String> lineComparator, boolean ignoreCase) throws IOException Sorts the input file into the output file using the supplied delimited line parameters. This method is not reliable when the sort field may contain Unicode codepoints outside the Basic Multilingual Plane, i.e. above . In that case, the sort order differs from Java's String sort order. This should not be a problem for most usage; the Supplementary Multilingual Planes contain ancient scripts, emojis, arrows and so on. This method is globally synchronized, in case multiple sorts are attempted to the same file simultaneously. This could be improved to allow synchronizing against the destination file, rather than for all sorts.- Parameters:
input- To sortsorted- The sorted version of the input excluding ignored header lines (see ignoreHeaderLines)column- the column that keeps the values to sort oncolumnDelimiter- the delimiter that separates columns in a rowenclosedBy- optional column enclosing character, e.g. a double quote for CSVsnewlineDelimiter- the chars used for new lines, usually \n, \r\n or \rignoreHeaderLines- number of beginning lines to ignore, e.g. headerslineComparator- used to sort the outputignoreCase- ignore case order, this parameter couldn't have any effect if the LineComparator is used- Throws:
IOException
-
sort
public void sort(List<File> inputs, File sorted, String encoding, int column, String columnDelimiter, Character enclosedBy, String newlineDelimiter, int ignoreHeaderLines, Comparator<String> lineComparator, boolean ignoreCase) throws IOException Sorts the input file into the output file using the supplied delimited line parameters. This method is not reliable when the sort field may contain Unicode codepoints outside the Basic Multilingual Plane, i.e. above . In that case, the sort order differs from Java's String sort order. This should not be a problem for most usage; the Supplementary Multilingual Planes contain ancient scripts, emojis, arrows and so on. This method is globally synchronized, in case multiple sorts are attempted to the same file simultaneously. This could be improved to allow synchronizing against the destination file, rather than for all sorts.- Parameters:
inputs- To sortsorted- The sorted version of the input excluding ignored header lines (see ignoreHeaderLines)column- the column that keeps the values to sort oncolumnDelimiter- the delimiter that separates columns in a rowenclosedBy- optional column enclosing character, e.g. a double quote for CSVsnewlineDelimiter- the chars used for new lines, usually \n, \r\n or \rignoreHeaderLines- number of beginning lines to ignore, e.g. headerslineComparator- used to sort the outputignoreCase- ignore case order, this parameter couldn't have any effect if the LineComparator is used- Throws:
IOException
-
sortInJava
public void sortInJava(File input, File sorted, String encoding, Comparator<String> lineComparator, int ignoreHeaderLines) throws IOException Sorts the input file into the output file using the supplied lineComparator.- Parameters:
input- To sortsorted- The sorted version of the input excluding ignored header lines (see ignoreHeaderLines)lineComparator- To use during comparisonignoreHeaderLines- number of beginning lines to ignore, e.g. headers- Throws:
IOException
-
sortInJava
public void sortInJava(List<File> inputs, File sorted, String encoding, Comparator<String> lineComparator, int ignoreHeaderLines) throws IOException Sorts the input file into the output file using the supplied lineComparator.- Parameters:
inputs- To sortsorted- The sorted version of the input excluding ignored header lines (see ignoreHeaderLines)lineComparator- To use during comparisonignoreHeaderLines- number of beginning lines to ignore, e.g. headers- Throws:
IOException
-
split
Splits the supplied file into files of set line size and with a suffix.- Parameters:
input- To split uplinesPerOutput- Lines per split fileextension- The file extension to use - e.g. ".txt"- Returns:
- The split files
- Throws:
IOException
-
touch
Creates an empty file or updates the last updated timestamp on the same as the unix command of the same name.From Guava.
- Parameters:
file- the file to create or update- Throws:
IOException- if an I/O error occurs
-
getFileExtension
Returns the file extension for the given file name, or the empty string if the file has no extension. The result does not include the '.'.Note: This method simply returns everything after the last '
.' in the file's name as determined byFile.getName(). It does not account for any filesystem-specific behavior that theFileAPI does not already account for. For example, on NTFS it will report"txt"as the extension for the filename"foo.exe:.txt"even though NTFS will drop the":.txt"part of the name when the file is actually created on the filesystem due to NTFS's Alternate Data Streams.From Guava.
-
createParentDirs
Creates any necessary but nonexistent parent directories of the specified file. Note that if this operation fails it may have succeeded in creating some (but not all) of the necessary parent directories.From Guava.
- Throws:
IOException- if an I/O error occurs, or if any necessary but nonexistent parent directories of the specified file could not be created.
-