org.apache.commons.io - FileUtils Learning Notes

Keywords: Java encoding JSP

Application of FileUtils Class

1. Write a file;

2. Read from the file;

3. Create a folder, including folders;

4. Copy files and folders;

5. Delete files and folders;

6. Get the file from the URL address.

7. List files and folders through file filters and extensions.

8. Compare the contents of documents;

9. The last modification time of the document;

10. Calculate checksum.

 

1. Method of copying files or folders:

Examples:

 1 public class CopyFileorDirectory {
 2     public static void main(String[] args) throws Exception {
 3         File file1 =new File("path1");
 4         File file2 =new File("path2");
 5         File file3 =new File("path3");
 6         File file4 =new File("path4");
 7         File file5 =new File("path5");
 8         //Copy the file to the specified folder and save the date of the file.
 9         // This method copies the contents of the specified source file to files with the same name in the specified target directory.
10         // If it does not exist, create the target directory. If the target file exists, the method overrides it.
11         FileUtils.copyFileToDirectory(file1,file2);//Documents are not fatal
12         //Copy the file to a new place (rename the file) and save the date of the file.
13         FileUtils.copyFile(file1,file3);
14 
15         //Copy the folder to the specified directory and create it if the specified directory does not exist
16         FileUtils.copyDirectoryToDirectory(file2,file4);
17 
18         //Copy folders to specified directories and rename them
19         FileUtils.copyDirectory(file4,file5);
20 
21         //This method copies the specified source directory structure to the specified target directory.
22         FileUtils.copyDirectory(file4,file5, DirectoryFileFilter.DIRECTORY);
23 
24         // Copy the suffix file specified in the first level content under the folder
25         IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt");
26         IOFileFilter txtFiles = FileFilterUtils.and(FileFileFilter.FILE, txtSuffixFilter);
27         FileUtils.copyDirectory(file4,file5, txtFiles);
28 
29         // Copy the file directory structure and the specified suffix files in the first level directory under the folder
30         FileFilter filter = FileFilterUtils.or(DirectoryFileFilter.DIRECTORY, txtFiles);
31         FileUtils.copyDirectory(file4,file5, filter,false);//The preserveFileDate parameter defaults to true.
32 
33         //Copy bytes from the URL source to the file destination. If they do not yet exist, a directory to the destination is created. If it already exists, the file will be overwritten.
34         URL source = new URL("http://imgsrc.baidu.com/baike/pic/ewe.jpg");
35         FileUtils.copyURLToFile(source,file5,1000,1000);
36 
37         // Wait for NFS to propagate file creation and enforce timeout. This method repeatedly tests File.exists() until it returns true, or until the maximum time specified in seconds.
38         File file = new File("/abc/");
39         boolean d = FileUtils.waitFor(file,100);
40         System.out.println(d);
41     }
42 }

2. Method of deleting files or files

 1 public class FileorDirectoryDelete {
 2     public static void main(String[] args) throws Exception{
 3         File file = new File("path1");
 4         File directory = new File("path2");
 5         //Remove a directory (including content) recursively.
 6         FileUtils.deleteDirectory(directory);
 7 
 8         //Delete a file without throwing an exception. If the file is a directory, delete it and all subdirectories.
 9         FileUtils.deleteQuietly(file);
10 
11         //Clean up the content without deleting it.
12         FileUtils.cleanDirectory(directory);
13 
14         //Deleting a file throws an exception
15         //If the file is a folder, delete all the contents of the folder and folder. If the file is a file, delete it.
16         //If a file/folder cannot be deleted for some reason, an exception is thrown
17         FileUtils.forceDelete(file);
18     }
19 }

III. Creating Catalogues

 1 public class CreatDirectory {
 2     public static void main(String[] args) throws Exception {
 3         File file = new File("path");
 4         //Create a folder and throw an exception if it cannot be created for some reason
 5         //One-level or multi-level directories can be created at a time
 6         FileUtils.forceMkdir(new File("/Users/wuguibin/Downloads/folder"));
 7         //Create the parent directory of the file for the specified file
 8         FileUtils.forceMkdirParent(file);
 9     }
10 }

4. Moving files or folders

//Move folders and rename them
FileUtils.moveDirectory(new File("/Users/Downloads/file1"),
       new File("/Users/Downloads/file2/file3"));

//Move the folder and give whether to rename it or not
FileUtils.moveDirectoryToDirectory(new File("/Users/Downloads/file1"),
       new File("/Users/Downloads/file2/"),false);
//Move the file to the specified folder and rename it FileUtils.moveFile(file1,new File("/Users/Downloads/Sea grape.jpen"));
//Move the file to the specified folder and specify whether or not to create the folder FileUtils.moveFileToDirectory(new File("/Users/Downloads/Sea grape.jpeg"), new File("/Users/Downloads/file2"),false);

5. Determine whether a file is the same or contains relationships, and obtain file or folder sizes

//Determines whether the parent directory contains the specified child element (a file or directory). That is, whether directory contains file2 or not, before comparison, files are standardized.
boolean a = FileUtils.directoryContains(directory,file2);
//Compare the contents of the two files to determine whether they are the same.
boolean b = FileUtils.contentEquals(file1, file2)

//Gets the specified file or folder size, which may overflow to a negative value
long l = FileUtils.sizeOf(file1);
System.out.println(l+"KB");
//Gets the specified file or folder size without overflowing
BigInteger bi= FileUtils.sizeOfAsBigInteger(file1);
System.out.println(bi+"kb");

//Recursively calculates the size of a directory (the sum of the lengths of all files).
//Note that sizeOfDirectory () does not detect an overflow, and if the overflow occurs, the return value may be negative. The sizeOfDirectoryAsBigInteger() method does not overflow.
FileUtils.sizeOfDirectory(file1);
FileUtils.sizeOfDirectoryAsBigInteger(file1);

6. Comparing old and new documents

  //Compare whether the specified file is created or modified later than the reference file
  boolean b = FileUtils.isFileNewer(file1,file2));
 
  //If the specified file is updated more than the specified date.
  SimpleDateFormat date = new SimpleDateFormat("yyyy/MM/dd");
  String date1 = "2017/06/20";
  boolean c = FileUtils.isFileNewer(file1,date.parse(date1));
  boolean d = FileUtils.isFileNewer(file1,23243);
        
   //Specifies whether a file is created or modified earlier than a reference file or date
   FileUtils.isFileOlder(file1,232434);
   FileUtils.isFileOlder(file1,System.currentTimeMillis());

VII. Writing to Documents

 //Writes the contents of the collection to a file to end the writing with the specified string
//void writeLines(File file,Collection<?> lines,String lineEnding,boolean append)
ArrayList<String> list = new ArrayList<>(); String str1 = "Java"; String str2 = "JSP"; list.add(str1); list.add(str2); FileUtils.writeLines(file8,"GBK",list,"java",true);
//Write strings to files //Parametric 1: Files that need to be written will be created automatically if they do not exist. Parametric 2: What needs to be written //Parametric 3: Encoding format parameter 4: Whether it is an additional mode (ture: additional mode, appending a string to the original content) String data1 = "earnest"; FileUtils.writeStringToFile(file,data1, "UTF-8", true); //Write byte arrays to files byte [] buf = {13,123,34}; System.out.println(new String(buf)); FileUtils.writeByteArrayToFile(file13,buf,0,buf.length,true);

8. Reading Files and Obtaining Input and Output Streams

 //Read the contents of the file into a string.
 String str =  FileUtils.readFileToString(file,"UTF-16" ); 
 FileUtils.readFileToByteArray(file);
 //Read files into byte arrays
 byte[] readFileToByteArray(final File file)

 //Read files into strings; Charset encoding: Encoding format
 String readFileToString(final File file, final Charset encoding)

 //Read the file into a set of strings; Charset encoding: Encoding format
 List<String> list4 =FileUtils.readLines(
       new File("/Users/Shared/note/java.txt"),"UTF-8");
 Iterator it = list4.iterator();
 while (it.hasNext()){
      Object obj=it.next();
      System.out.println(obj);
  }


 //Get the input stream
FileUtils.openInputStream(file);
 //Get the output stream
FileUtils.openOutputStream(file);

Posted by erisande on Mon, 11 Feb 2019 18:33:18 -0800