An overview,
Apache Commons IO is a component of Apache Commons that is derived from the Java API and provides a variety of utility classes for common operations on file IO, covering a variety of use cases and greatly simplifying our code for working with IO streams and manipulating files. Java IO manipulation is a common technique in development, but it can be tedious to use native IO streams every time. For example, the code to read a web page’s source code might look like this:
InputStream in = new URL("http://commons.apache.org").openStream();
try {
InputStreamReader inR = new InputStreamReader(in);
BufferedReader buf = new BufferedReader(inR);
String line;
while((line = buf.readLine()) ! =null) { System.out.println(line); }}finally {
in.close();
}
Copy the code
With Commons IO, you can greatly simplify the code as follows:
InputStream in = new URL("http://commons.apache.org").openStream();
try {
System.out.println(IOUtils.toString(in, "UTF-8"));
} finally {
IOUtils.close(in);
}
Copy the code
2. Common classes
The Apache Commons IO library provides classes in the following categories
package | instructions |
---|---|
org.apache.commons.io | About streams, Readers, Writers, files and other entities and tools |
org.apache.commons.io.comparator | File comparison and sorting |
org.apache.commons.io.filefilter | Filter files based on logical criteria |
org.apache.commons.io.input | File input (InputStream, Reader) implementation |
org.apache.commons.io.monitor | Monitor for document tracking and related events |
org.apache.commons.io.output | File output (OutputStream, Writer) implementation |
org.apache.commons.io.serialization | serialization |
2.1 tools
The utility classes include FileUtils, IOUtils, and FilenameUtils. The methods of these three are not very different, except for the objects they operate on. As the name suggests, FileUtils operates on the File class, IOUtils operates on IO streams, and FilenameUtils operates on File names.
2.1.2 IOUtils
IOUtils contains utility classes for handling read, write, and copy methods for InputStream, OutputStream, Reader, and Writer.
methods | instructions |
---|---|
BufferedInputStream buffer(InputStream inputStream) | Wrap the incoming stream as a buffer stream. The buffer size can be specified by parameter |
close(Closeable closeable) | Close the stream |
closeQuietly(Closeable closeable) | Close the stream |
contentEquals(InputStream input1,InputStream input2) | Compares whether the contents of two streams are equal |
contentEqualsIgnoreEOL(Reader reader1,Reader reader2) | Compare two streams, ignoring newlines |
copy(InputStream input,OutputStream output) | Copies the contents of an input stream to an output stream and can specify a character encoding This method has multiple overloaded methods for different input and output streams |
copyLarge(InputStream input,OutputStream output) | Copy the content from the input stream to the output stream. This method is suitable for copying the content larger than 2G |
LineIterator lineIterator(InputStream input,Charset charset) | Read the stream and return the iterator |
read(InputStream input,byte[] buffer) | Read content from a stream |
readFully(InputStream input,byte[] buffer) | Reads everything from the input stream into a byte array |
List<String> readLines(InputStream input,Charset charset) | String reading and writing |
String resourceToString(String name,Charset charset) | |
URL resourceToURL(String name) | |
long skip(InputStream input,long toSkip) | Skips streams of specified length |
skipFully(InputStream input,long toSkip) | Similar to Skip, except that an exception is thrown if the ignored length is greater than the existing length |
toBufferedInputStream(InputStream input) | Gets a buffered input stream, with a default buffered size of 1KB |
toBufferedReader(Reader reader) | Gets a character buffer stream |
toByteArray(InputStream inputStream) | Replaces the input stream with an array of characters |
toInputStream(CharSequence input,Charset charset) | Get the input stream from text, and you can specify the encoding format |
toString(InputStream input,Charset charset) | Converts the input stream to a string |
write(byte[] data,OutputStream output) | Write data to the output stream |
@Test
public void testIOUtils(a) throws IOException, URISyntaxException {
String fileDir = "/Users/dllwh/Downloads/test";
String file1 = fileDir + File.separator + "aa.txt";
String file2 = fileDir + File.separator + "bb.txt";
String charsetName = "UTF-8";
String urlStr = "http://www.baidu.com";
FileInputStream fileInputStream1 = new FileInputStream(file1);
FileInputStream fileInputStream2 = new FileInputStream(file2);
FileOutputStream outputStream = new FileOutputStream(file1);
FileReader fileReader1 = new FileReader(file1);
FileReader fileReader2 = new FileReader(file1);
FileWriter fileWriter = new FileWriter(file1);
/** * 1, */
//
System.out.println("1.1 Obtaining file Path Separator Characters:" + IOUtils.DIR_SEPARATOR);
System.out.println("1.2 Obtaining the Unix System File Path Separator Character:" + IOUtils.DIR_SEPARATOR_UNIX);
System.out.println("1.3 Obtaining the File Path Separator for Windows:" + IOUtils.DIR_SEPARATOR_WINDOWS);
System.out.println("1.4 Obtaining line separator:" + IOUtils.LINE_SEPARATOR);
System.out.println("1.5 Obtaining the Unix System Line separator:" + IOUtils.LINE_SEPARATOR_UNIX);
System.out.println("1.6 Obtaining the Line Separator for Windows:" + IOUtils.LINE_SEPARATOR_WINDOWS);
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** ** /
//2.1 Get input stream
System.out.println("2.1 Obtain BufferedInputStream from InputStream:" + IOUtils.buffer(fileInputStream1));
System.out.println("2.2 Get BufferedOutputStream from outputStream: + IOUtils.buffer(outputStream));
System.out.println("2.3 Get BufferedReader from reader:" + IOUtils.buffer(fileReader1));
System.out.println("2.4 getting row data from InputStream InputStream:");
List<String> lineContent = IOUtils.readLines(fileInputStream1, "UTF-8");
lineContent.forEach(s -> System.out.println(s));
System.out.println("2.5 Obtaining row data from Reader input stream:");
IOUtils.readLines(fileReader1).forEach(s -> System.out.println(s));
byte[] data = IOUtils.toByteArray(fileInputStream1);
System.out.println("2.6 Getting file byte arrays from inputStream:" + data);
System.out.println("2.7 Get file byte array from Reader and specify encoding:" + IOUtils.toByteArray(fileReader1, charsetName));
System.out.println("2.8 Retrieving file byte arrays from URL resources:" + IOUtils.toByteArray(new URI(urlStr)));
char[] charData = IOUtils.toCharArray(fileInputStream1, "UTF-8");
System.out.println("2.9 Getting character data from InputStream:" + charData);
System.out.println("2.10 Obtaining an array of characters from the reader input stream:" + IOUtils.toCharArray(fileReader1));
System.out.println("2.11 Getting string data from InputStream:" + IOUtils.toString(fileInputStream1, charsetName));
System.out.println("2.12 Retrieving string data from reader input stream:" + IOUtils.toString(fileReader1));
System.out.println("2.13 Getting string data from URL:" + IOUtils.toString(new URI(urlStr), charsetName));
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** * 3, write data */
System.out.println("3.1 Write byte array data to file via Writer and specify encoding");
IOUtils.write(data, fileWriter, charsetName);
System.out.println("3.2 Writing byte Array data to file via outputStream");
IOUtils.write(charData, outputStream, charsetName);
System.out.println("3.3 Writing character array data to a file via Writer");
IOUtils.write(charData, fileWriter);
System.out.println(3.4 Writing string data to a file via OutpurStream);
IOUtils.write("Time gone, step tottering, broken silver a few two men difficult.", outputStream, charsetName);
System.out.println(3.5 Writing String Data to a File through the Writer output stream);
IOUtils.write("I used to dream of a better life, and I looked back and wished only for the old and the young.", fileWriter);
System.out.println("3.6 Write set data to a file through outputStream");
IOUtils.writeLines(lineContent, "UTF-8", outputStream, charsetName);
System.out.println("3.7 Writing collection Data to a file via writer output stream");
IOUtils.writeLines(lineContent, "UTF-8", fileWriter);
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** * 4, get the file input iterator */
System.out.println(4.1 obtaining a row iterator from an inputStream inputStream);
LineIterator lineIterator = IOUtils.lineIterator(fileInputStream1, charsetName);
System.out.println(4.2 Obtaining a Row iterator from the Reader input stream);
LineIterator lineIterator1 = IOUtils.lineIterator(fileReader1);
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/**
* 5、复制文件
*/
System.out.println("5.1 Copying file input stream to output stream:"+IOUtils.copy(fileInputStream1, outputStream));
System.out.println("5.2 Copy file input stream to output stream and set buffer size:"+IOUtils.copy(fileInputStream1, outputStream, 1024));
System.out.println("5.3 Copy the InputStream file to the output stream Writer and set the output stream encoding :");
IOUtils.copy(fileInputStream1, fileWriter, charsetName);
System.out.println("5.4 Copying Reader files to Writer");
IOUtils.copy(fileReader1, fileWriter);
System.out.println(5.5 Copying large Files from inputStream to outputStream larger than 2g:);
IOUtils.copy(fileInputStream1, outputStream);
System.out.println("5.6 Copying a Large File From Reader to Writer Whose file size Exceeds 2g");
IOUtils.copy(fileReader1, fileWriter);
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** ** /
System.out.println(6.1 Comparing two InputStreams for equality:+IOUtils.contentEquals(fileInputStream1, fileInputStream2));
System.out.println("6.2 Determine whether two readers are equal:"+IOUtils.contentEquals(fileReader1, fileReader2));
}
Copy the code
2.1.2 FilenameUtils
FilenameUtils contains utility classes that work based on File names rather than File objects. It runs similarly on different operating systems, addressing the issue of moving from a Windows-based development environment to a Unix-based production environment.
methods | instructions |
---|---|
String concat(String basePath,String fileName) | Merge directory and file name file full path |
directoryContains(String directory,String child) | Check whether the directory contains the specified file or directory |
equals(String fileName1,String fileName2) | Check whether the file paths are the same |
String getBaseName(String fileName) | Gets the file name with the directory and suffix removed |
String getExtension(String fileName) | Gets the suffix of the file |
String getFullPath(String fileName) | Gets the directory of the file |
String getName(String fileName) | Gets the file name, including the suffix |
String getPath(String fileName) | Path after the drive letter is removed |
String getPrefix(String fileName) | Gets the prefix, known as the drive letter |
indexOfExtension(String fileName) | Gets the position of the last |
indexOfLastSeparator(String fileName) | Gets the position of the last / |
isExtension(String fileName,String… extension) | Checks whether the file extension is included in the specified collection |
String normalize(String fileName,boolean separator) | Gets the current system formatting path |
String removeExtension(String fileName) | Remove the file extension |
String separatorsToSystem(String path) | Convert the separator to the current system separator |
String separatorsToUnix(String path) | Convert delimiters to Linux system delimiters |
String separatorsToWindows(String path) | Convert the separator to a Windows system separator |
wildcardMatch(String fileName,String matcher) | Checks whether the file name extension matches the specified rule |
@Test
public void testFilenameUtil(a) {
String fileDir = "/Users/dllwh/Downloads";
String file1 = fileDir + File.separator + "07e92f6d1ec2b1aaa0fcabe135413a20.jpg";
String file2 = fileDir + File.separator + "1bf898a2a6986716634299d0f16eda99.jpg";
String file3 = fileDir + File.separator + "8ee0d1306cfd7fa00340199ff859b03d.jpg";
System.out.println("1. Determine whether the parent directory contains child elements (files or directories):" + FilenameUtils.directoryContains(fileDir, file2));
System.out.println("2. Check whether two file names are equal:" + FilenameUtils.equals(fileDir, file1));
System.out.println("3. Determine whether the two file names are equal after standardization:" + FilenameUtils.equalsNormalized(fileDir, file1));
System.out.println("4. Get file base name:" + FilenameUtils.getBaseName(file3));
System.out.println("5. Obtain file extension:" + FilenameUtils.getExtension(file3));
System.out.println("6. Obtain the full file path without file name:" + FilenameUtils.getFullPath(file3));
System.out.println("7. Get full path to file without ending delimiter, without filename:" + FilenameUtils.getFullPathNoEndSeparator(file3));
System.out.println("8. Get a separate file name and suffix:" + FilenameUtils.getName(file3));
System.out.println("9. Get full file path without prefix, without filename:" + FilenameUtils.getPath(file3));
System.out.println("10. Get full file path without prefix and ending delimiter, without filename:" + FilenameUtils.getPathNoEndSeparator(file3));
System.out.println("11. Get file path prefix:" + FilenameUtils.getPrefix(file3));
System.out.println("12. Obtain file path prefix length:" + FilenameUtils.getPrefixLength(file3));
System.out.println("13. Get file extension index:" + FilenameUtils.indexOfExtension(file3));
System.out.println("14. Get last delimiter index of file:" + FilenameUtils.indexOfLastSeparator(file3));
List<String> suffixList = new ArrayList<String>();
suffixList.add("png");
suffixList.add("txt");
suffixList.add("xlsx");
System.out.println("15. Determine whether the file extension matches the given:" + FilenameUtils.isExtension(file3, suffixList));
System.out.println("16. Determine whether the file extension matches the specified:" + FilenameUtils.isExtension(file3, "jpg"));
System.out.println("17. Standardized file path:" + FilenameUtils.normalize(file3));
System.out.println("18. Standardized file path without final trailing delimiter:" + FilenameUtils.normalizeNoEndSeparator(file3));
System.out.println("19. Get file path and file name without suffix:" + FilenameUtils.removeExtension(file3));
System.out.println("20. Convert file separator to system separator:" + FilenameUtils.separatorsToSystem(file3));
System.out.println("21. Convert file separator to Unix system separator:" + FilenameUtils.separatorsToUnix(file3));
System.out.println("22. Convert file separator to Windows system separator:" + FilenameUtils.separatorsToWindows(file3));
System.out.println("23. Determine whether the file name complies with the specified rule:" + FilenameUtils.wildcardMatch(file3, "*.jpg"));
}
Copy the code
2.1.3 FileUtils
Contains methods related to file operations, such as moving, opening, checking for existence, reading files, etc.
methods | instructions |
---|---|
String byteCountToDisplaySize(BigInteger size) | |
void cleanDirectory(File directory) | Clear all contents of folders (including subfolders and subfiles) |
boolean contentEquals(File file1,File file2) | Compare two files to see if they have the same content |
copyDirectory(File srcDir,File destDir) | Copy the contents of one directory to another directory |
copyDirectoryToDirectory(File sourceDir,File destDir) | Copy a folder as a subdirectory to another folder |
copyFile(File srcFile,File destFile) | Copy the file |
copyFileToDirectory(File srcFile,File destDir) | Copy files to a directory |
copyInputStreamToFile(InputStream source,File dest) | Copies the contents of the input stream to a file |
copyToDirectory(File sourceFile,File destDir) | |
copyToFile(InputStream inputStream,File file) | |
copyURLToFile(URL source,File destination) | Copy the contents of the URL to a file (you can download the file) |
File delete(File file) | delete |
void deleteDirectory(File directory) | Delete folders, including folders and all files in folders |
boolean deleteQuietly(File file) | Delete the file |
directoryContains(File directory,File child) | Check whether the folder contains a file or folder |
void forceDelete(File file) | Deletes a file forcibly, or raises an exception if the file does not exist |
void forceDeleteOnExit(File file) | |
void forceMkdir(File directory) | Create a folder (multiple levels can be created) |
void forceMkdirParent(File file) | Create the parent directory of the file |
File getFile(File directory,String… names) | Gets the file from the specified folder |
File getFile(String… names) | |
File getTempDirectory() | Get temporary directory files |
String getTempDirectoryPath() | Gets the temporary directory path |
File getUserDirectory() | Get the user directory file |
String getUserDirectoryPath() | Gets the user directory path |
boolean isFileNewer(File file,File reference) | Check whether file is new compared to reference |
boolean isFileNewer(File file,Date date) | Checks whether a file is new on the specified date |
boolean isFileOlder(File file,File reference) | |
boolean isRegularFile(File file,LinkOption… options) | |
boolean isSymlink(File file) | Check whether it is a symbolic link |
LineIterator lineIterator(final File file) | |
listFiles(File directory,IOFileFilter fileFilter,IOFileFilter dirFilter) | Lists the files in the specified directory |
listFiles(File directory,String[] extensions,boolean recursive) | Whether to recursively find files with the specified extension |
listFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) | Query all files in the directory and use filter to filter |
moveDirectory(File srcDir,File destDir) | All files inside the folder will be moved |
moveDirectoryToDirectory(File src,File destDir,boolean createDestDir) | Move to another file as a subfolder |
moveFile(File srcFile,File destFile) | Move files |
moveFileToDirectory(File srcFile,File destDir,boolean createDestDir) | Move it as a subfile to another folder |
moveToDirectory(File src,File destDir,boolean createDestDir) | Move a file or directory to a specified folder |
FileInputStream openInputStream(File file) | Gets the file read stream, overwriting the file content directly by default |
FileOutputStream openOutputStream(File file,boolean append) | Gets the file output stream and specifies whether to append to the file |
byte[] readFileToByteArray(File file) | Read the file into a byte array |
String readFileToString(File file,String charsetName) | Read the file as a string |
List<String> readLines(File file,String charsetName) | Read a file as a collection of strings |
long sizeOf(File file) | Gets the size of a file or folder |
File toFile(URL url) | |
File[] toFiles(URL… urls) | |
touch(final File file) | Creating an empty file |
write(File file,CharSequence data,String charsetName) | Write content into the file |
writeByteArrayToFile(File file,byte[] data,int off,int len,boolean append) | Write file, the file does not exist automatically created, and specify whether to append |
writeLines(File file,Collection<? > lines,String lineEnding,boolean append) | Write file by line, file does not exist automatically created, and specify whether to append |
writeStringToFile(File file,String data,String charsetName,boolean append) | Specifies the encoding and whether to append to the file |
@Test
public void testFileUtil(a) throws IOException {
String fileDirPath = "/Users/dllwh/Downloads/test";
String destDirPath = "/Users/dllwh/Downloads/test1";
String file1Name = "aa.txt";
String file2Nme = "bb.txt";
/** * 1, create file \ folder */
File file = FileUtils.getFile(new File(fileDirPath), file1Name);
System.out.println("1.1 Obtaining a specified file from a folder:" + file);
System.out.println("1.2 Obtaining obtaining temporary files:" + FileUtils.getTempDirectory());
System.out.println("1.3 Obtaining temporary File path:" + FileUtils.getTempDirectoryPath());
System.out.println("1.4 Obtaining User Files:" + FileUtils.getUserDirectory());
System.out.println("1.5 Obtaining user File Path:" + FileUtils.getUserDirectoryPath());
System.out.println("1.6 Forcibly Creating a Folder");
FileUtils.forceMkdir(new File(fileDirPath));
System.out.println("1.7 Forcibly Creating a Parent Folder");
FileUtils.forceMkdirParent(new File(fileDirPath, file1Name));
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** * 2, delete file */
System.out.println("2.1 Deleting contents of folders (including subfolders and subfiles)");
FileUtils.cleanDirectory(new File(fileDirPath));
System.out.println("2.2 Gently delete files without throwing exceptions");
FileUtils.deleteQuietly(new File(fileDirPath, file1Name));
System.out.println("2.3 Forcibly Deleting a File. The file must exist; otherwise, an exception will be thrown.");
FileUtils.touch(new File(fileDirPath,file1Name));
FileUtils.forceDelete(new File(fileDirPath, file1Name));
System.out.println("2.4 Forcibly Deleting files upon JVM Exit");
FileUtils.forceDeleteOnExit(new File(fileDirPath, file1Name));
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** * 3
System.out.println("3.1 Moving Folders");
if (new File(destDirPath).exists()) {
FileUtils.forceDelete(new File(destDirPath));
}
FileUtils.moveDirectory(new File(fileDirPath), new File(destDirPath));
System.out.println("3.2 Moving files to the specified folder");
FileUtils.touch(new File(fileDirPath, file1Name));
FileUtils.moveFileToDirectory(new File(fileDirPath, file1Name), new File(destDirPath), true);
System.out.println("3.3 Moving a file or folder to a specified folder");
FileUtils.moveToDirectory(new File(destDirPath, file1Name), new File(fileDirPath), true);
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** **
System.out.println("4.1 Whether to recursively find files with the specified extension");
String[] extensions = new String[]{"txt"."jpg"."png"};
Collection<File> fileList = FileUtils.listFiles(new File(fileDirPath), extensions, true);
fileList.forEach(f -> System.out.println(f.getAbsolutePath()));
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** ** /
System.out.println("5.1 Obtaining file input stream from file:" + FileUtils.openInputStream(new File(fileDirPath,file1Name)));
byte[] bytes = FileUtils.readFileToByteArray(new File(fileDirPath,file1Name));
System.out.println("5.2 Reading files into byte Arrays:" + Arrays.toString(bytes));
String fileContent = FileUtils.readFileToString(new File(fileDirPath,file1Name), "UTF-8");
System.out.println("5.3 Reading files into strings:" + fileContent);
System.out.println("5.4 Reading files into collections:");
List<String> fileContentList = FileUtils.readLines(new File(fileDirPath,file1Name), "UTF-8");
fileContentList.forEach(System.out::println);
System.out.println("5.5 Obtaining file Size:" + FileUtils.sizeOf(new File(fileDirPath,file1Name)));
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** * 6, write file */
System.out.println("6.1 Obtaining output stream from file:" + FileUtils.openOutputStream(new File(fileDirPath,file1Name)));
System.out.println("6.2 Get file output stream and specify whether to append to file:" + FileUtils.openOutputStream(new File(fileDirPath,file1Name), true));
System.out.println("6.3 Writing byte array contents to file if file does not exist:");
FileUtils.writeByteArrayToFile(new File(fileDirPath,file1Name), bytes);
System.out.println(6.4 Write byte array contents to file, create if file does not exist, and specify whether to append:);
FileUtils.writeByteArrayToFile(new File(fileDirPath,file1Name), bytes, true);
System.out.println("6.5 Write collection data line by line to file:");
FileUtils.writeLines(new File(fileDirPath,file1Name), fileContentList);
System.out.println("6.6 Write collection data to file by line and specify whether to append:");
FileUtils.writeLines(new File(fileDirPath,file1Name), fileContentList, true);
System.out.println("6.7 Write string to file and specify encoding:");
FileUtils.writeStringToFile(file, fileContent, "UTF-8");
System.out.println("6.8 Write string data to file and specify encoding and appending method:");
FileUtils.writeStringToFile(file, fileContent, "UTF-8".true);
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** * 7, copy file */
System.out.println("7.1 Copying contents of a file directory to another directory");
File fileDir = new File(fileDirPath);
File destDir = new File(destDirPath);
FileUtils.copyDirectory(fileDir, destDir);
System.out.println("7.2 Copy the file directory and specify whether to save the file date");
FileUtils.copyDirectory(fileDir, destDir, true);
System.out.println("7.3 Filtering Files using file Filters");
FileUtils.copyDirectory(fileDir, destDir, new NameFileFilter("aa"));
System.out.println("7.4 Copying files");
FileUtils.copyFile(new File(fileDirPath,file1Name), new File(destDirPath,file2Nme));
System.out.println("7.5 Copy the file and specify whether to retain the file date");
FileUtils.copyDirectory(new File(fileDirPath), new File(destDirPath), true);
System.out.println("7.6 Copying folders to directories");
FileUtils.copyFileToDirectory(new File(fileDirPath,file1Name), destDir);
System.out.println("7.7 Copying URL Resources to a Specified File");
FileUtils.copyURLToFile(new URL("http://www.baidu.com"), file);
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** **
System.out.println("8.1 List descendant directories or files with filtering function");
for (File f : FileUtils.listFiles(new File(fileDirPath), EmptyFileFilter.NOT_EMPTY, null)) {
System.out.println(f.getAbsolutePath());
}
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** * 9
System.out.println(9.1 Comparing whether file Contents are The same: + FileUtils.contentEquals(new File(fileDirPath,file1Name), new File(destDirPath,file2Nme)));
System.out.println("9.2 Determining whether a folder contains another folder:" + FileUtils.directoryContains(new File(fileDirPath), new File(destDirPath)));
System.out.println("9.3 Checking whether a File is new (isFileNewer):" + FileUtils.isFileNewer(new File(fileDirPath,file1Name), new Date()));
System.out.println("9.3 Checking whether a file is new (isFileOlder):" + FileUtils.isFileOlder(new File(fileDirPath,file1Name), new Date()));
System.out.println("9.3 Determine whether a file is new compared to another file (isFileNewer):" + FileUtils.isFileNewer(new File(fileDirPath,file1Name), new File(destDirPath,file2Nme)));
System.out.println("9.3 Checking whether a file is new compared to another file (isFileOlder):" + FileUtils.isFileOlder(new File(fileDirPath,file1Name), new File(destDirPath,file2Nme)));
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** ** */
System.out.println(10.1 Converting a Collection of Files to an Array of files);
for (File f : FileUtils.convertFileCollectionToFileArray(fileList)) {
System.out.println(f.getAbsolutePath());
}
System.out.println("10.2 Converting URL Resources into File Objects" + FileUtils.toFile(new URL("http://www.baidu.com")));
System.out.println("10.3 Converting Multiple URL Resources into file Arrays");
File[] newUrlFiles1 = FileUtils.toFiles(new URL[]{});
for (File f : FileUtils.convertFileCollectionToFileArray(fileList)) {
System.out.println(f.getAbsolutePath());
}
System.out.println("10.4 Converting file Arrays to URL Resources");
for (URL url : FileUtils.toURLs(newUrlFiles1)) {
System.out.println(url.getPath());
}
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** *
System.out.println("11.1 File Iteration");
LineIterator iterator = FileUtils.lineIterator(new File(fileDirPath,file1Name), "UTF-8");
while(iterator.hasNext()) { System.out.println(iterator.next()); }}Copy the code
2.2 File Filters
Org.apache.com mons. IO. Filefilter package defines an interface (IOFileFilter), at the same time inherited Java. IO. Filefilter and Java. IO. FilenameFilter interface. There are also a number of IOFileFilter interface implementations that you can use, including allowing you to combine other filters. For example, these filters can be used to traverse files or in FileDialog.
category | Filter name | instructions |
---|---|---|
type | FileFileFilter | File only |
DirectoryFilter | Contents only | |
The name of the | PrefixFileFilter | Filter files based on prefixes |
SuffixFileFilter | Filter files by suffix, which is used to retrieve all files of a particular type | |
NameFileFilter | Filter files based on file names | |
WildcardFileFilter | Filter files based on wildcard characters | |
RegexFileFilter | Based on regular expressions | |
time | AgeFileFilter | Based on the last modification time |
The size of the | EmptyFileFilter | Based on whether a file or directory is empty |
SizeFileFilter | Based on file size | |
Hidden attribute | HiddenFileFilter | Based on whether files or directories are hidden |
Read and write attribute | CanReadFileFilter | Based on whether it is readable |
CanWriteFileFilter | Based on whether it can be written | |
Logical relation filter | AndFileFilter | Based on AND logic operation |
OrFileFilter | Based on OR logic operation | |
NotFileFilter | Based on NOT logic operation | |
Utility class | FileFilterUtils | Provides factory methods for generating various file filters Provides static methods to filter a specified collection of files |
@Test
public void testFileFilter(a) {
// Get the current directory
File fileDir = new File(".");
/** * Matches the file name */
String[] acceptedNames = {"input"."input.txt"};
for (String file : fileDir.list(new NameFileFilter(acceptedNames, IOCase.INSENSITIVE))) {
System.out.println("File found, named: " + file);
}
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** * Matches by wildcard (filters files whose names end in t) */
for (String file : fileDir.list(new WildcardFileFilter("*t"))) {
System.out.println("Wildcard file found, named: " + file);
}
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** * matches the suffix (filters files with the Java extension) */
for (String file : fileDir.list(new SuffixFileFilter("java"))) {
System.out.println("Suffix file found, named: " + file);
}
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** * matches the prefix */
for (String file : fileDir.list(new PrefixFileFilter("input"))) {
System.out.println("Prefix file found, named: " + file);
}
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** * logical or (filter files whose names start with. Or end with t) */
for (String file : fileDir.list(
new OrFileFilter(new PrefixFileFilter("."), new WildcardFileFilter("*t")))) {
System.out.println("Or file found, named: " + file);
}
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
/** * logic and (filter files whose names start with. And end with t) */
for (String file : fileDir.list(
new AndFileFilter(new PrefixFileFilter("."), new WildcardFileFilter("*t")))) {
System.out.println("And/Not file found, named: "+ file); }}Copy the code
2.3 File Monitoring
The thread of the FileAlterationMonitor in the file monitoring class scans the FileAlterationObserver at a specified interval (default: 1000 ms). If there is a file change, it determines whether to add or delete the file according to the relevant file comparator. Change it. Before we begin, let’s familiarize ourselves with a few classes related to file monitoring.
Monitor the class | instructions |
---|---|
FileEntry | Provides the state of a file or directory and file properties at a point in time |
FileAlterationObserver | File state in the root directory, checks the file system and notifies listeners of create, change, or delete events |
FileAlterationMonitor | Generates a thread that monitors the thread and triggers any registered FileAlterationObserver at a specified interval |
Next, let’s see how to implement file monitoring. The specific implementation logic is as follows:
- Create a FileAlterationObserver object, passing in a directory to monitor. This object can monitor folders, file creation, deletion, and modification.
- Add a FileAlterationListener object to an Observer by calling the addListener() method.
- There are a number of ways that you can create, inherit adapter classes or implement interfaces or use anonymous inner classes to implement the monitoring methods that you need.
- FileAlterationListener provides an interface for detecting folder and file change callbacks and for observing mode callbacks
- Create a FileAlterationMonitor object, add the already created Observer object to it and pass in the interval parameter (in milliseconds).
- Inheriting the Runnable interface, it detects files by using a thread to continuously inspect files
- Call the start() method to start the monitor, or if you want to stop the monitor, call the stop() method.
@Test
public void testFileMonitor(a) {
File inputFile = FileUtils.getFile("input.txt");
File parentDirectory = FileUtils.getFile(FilenameUtils.getFullPath(inputFile.getAbsolutePath()));
// Listen for file changes in the directory. Some files can be monitored by parameter control. By default, all files in the directory can be monitored
FileAlterationObserver observer = new FileAlterationObserver(parentDirectory);
// Set the file change listener
observer.addListener(new FileAlterationListenerAdaptor() {
@Override
public void onDirectoryCreate(File directory) {
System.out.println("Directory creation:" + directory.getName());
}
@Override
public void onDirectoryChange(File directory) {
System.out.println("Directory Modification:" + directory.getName());
}
@Override
public void onDirectoryDelete(File directory) {
System.out.println("Directory deletion:" + directory.getName());
}
@Override
public void onFileCreate(File file) {
System.out.println("File creation:" + file.getName());
}
@Override
public void onFileChange(File file) {
System.out.println("File Modification:" + file.getName());
}
@Override
public void onFileDelete(File file) {
System.out.println("File Deletion:"+ file.getName()); }});// Create a monitor to check for changes every 500 milliseconds
FileAlterationMonitor monitor = new FileAlterationMonitor(500, observer);
try {
// Start monitoring
monitor.start();
//create a new directory
File newFolder = new File("test");
File newFile = new File("test1");
newFolder.mkdirs();
Thread.sleep(1000);
newFile.createNewFile();
Thread.sleep(1000);
FileDeleteStrategy.NORMAL.delete(newFolder);
Thread.sleep(1000);
FileDeleteStrategy.NORMAL.delete(newFile);
Thread.sleep(1000);
// Stop monitoring
monitor.stop(10000);
} catch(Exception e) { System.out.println(e.getMessage()); }}Copy the code
2.4 the comparator
Org.apache.commons.io.com parator package for Java. IO. File provides some java.util.Com parator implementation, the comparator can be used to sort the list. In org.apache.commons.io.com parator package there are a lot of ready-made file under the comparator, can directly use to sort the file, as follows:
type | instructions |
---|---|
CompositeFileComparator | Combine sort, combining the following collation rules |
DefaultFileComparator | The default File comparator uses the File compare method directly |
DirectoryFileComparator | Directories come before files |
ExtensionFileComparator | The extension comparator sorts files in ASCII order by their extensions, with non-extended files always coming first |
LastModifiedFileComparator | Sort by last modified time of file |
NameFileComparator | Sort by file name |
PathFileComparator | Sort by path, and the parent directory takes precedence |
SizeFileComparator | Sort by file size, small files first (directories count their total size) |
By looking at the source code, the above classes have methods like compare, sort, and toString().
@Test
public void testFileComparator(a) {
// Get the current directory
File dirFile = new File(".");
NameFileComparator comparator = new NameFileComparator(IOCase.SENSITIVE);
for (File file : comparator.sort(dirFile.listFiles())) {
System.out.println(file.getAbsolutePath());
}
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
SizeFileComparator sizeComparator = new SizeFileComparator(true);
for (File file : sizeComparator.sort(dirFile.listFiles())) {
System.out.println(file.getName() + " with size (kb): " + file.length());
}
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
LastModifiedFileComparator lastModified = new LastModifiedFileComparator();
for (File file : lastModified.sort(dirFile.listFiles())) {
Date modified = new Date(file.lastModified());
System.out.println(file.getName() + " last modified on: "+ modified); }}Copy the code
2.5 Input and output
Org.apache.com mons. IO. Input and org.apache.com mons. IO. Many useful in the output packet filtering flow, here are a few do:
flow | instructions |
---|---|
AutoCloseInputStream | An automatically closed input stream |
ReversedLinesFileReader | Read files in reverse order |
CountingInputStream | A stream with a counting function |
CountingOutputStream | A stream with a counting function |
ObservableInputStream | Observable input stream (typical observer mode) for reading and processing |
BOMInputStream | Read the BOM header of the text file at the same time |
BoundedInputStream | A bounded stream whose control allows only the first x bytes to be read |
CharSequenceInputStream | Supports Reading StringBuilder and StringBuffer |
/** * AutoCloseInputStream is a filter used to wrap other streams, and the stream is automatically closed after reading * The implementation principle is simple, when finished reading the underlying stream close, and then create a ClosedInputStream assigned to its wrapped input stream. * note: If the input stream is not fully read, the underlying stream is not closed */
@Test
public void autoCloseDemo(a) throws Exception {
InputStream is = new FileInputStream("test.txt");
AutoCloseInputStream autoCloseInputStream = new AutoCloseInputStream(is);
// Read the entire stream
IOUtils.toByteArray(autoCloseInputStream);
// We can omit the logic to close the stream
}
/** * You can't exactly know the size of an input stream by giving it an input stream. The available() method is available only in the case of ByteArrayInputStream. Other streams, such as file.length (), are not accurate * (they can also be implemented in a wild way, such as writing a temporary File to file.length (), and then converting the File to stream) * the following stream can be used to count the size of the File after reading it */
@Test
public void countingDemo(a) throws FileNotFoundException {
InputStream is = new FileInputStream("test.txt");
try (CountingInputStream cis = new CountingInputStream(is)) {
// File contents
String txt = IOUtils.toString(cis, "UTF-8");
// The number of bytes read
long size = cis.getByteCount();
} catch (IOException e) {
// Exception handling}}private class MyObservableInputStream extends ObservableInputStream {
class MyObserver extends Observer {
@Override
public void data(final int input) throws IOException {
// Do custom processing
}
@Override
public void data(final byte[] input, final int offset, final int length) throws IOException {
// Do custom processing}}public MyObservableInputStream(InputStream inputStream) {
super(inputStream); }}Copy the code