Summary of Java IO Stream Learning VII: Commons IO 2.5-FileUtils

Keywords: Android encoding Java Apache xml

Summary of Java IO Stream Learning VII: Commons IO 2.5-FileUtils

For reprinting, please indicate the source: http://blog.csdn.net/zhaoyanjun6/article/details/54972773
This article is from [Zhao Yanjun's blog]

In the previous articles, I introduced the common use of IO, and today I introduce the use of the Commons IO framework.

Brief Introduction to Commons IO

Apache Commons IO is a Java library created and maintained by the Apache Foundation. It provides many classes that make common tasks for developers simpler while reducing duplication of code that may be pervasive in each individual project, but you have to write it repeatedly. These classes are maintained by experienced developers, considerate about the boundary conditions of various problems, and continue to fix related bug s. Latest version 2.5

Download address: http://commons.apache.org/proper/commons-io/download_io.cgi

FileUtils File Operating Tool Class

  • Copy folders
//Copy folders (the contents of files in folders will also be copied), file1 and file2 level.
//Parameter 1: folder; parameter 2: folder
void copyDirectory( file1 , file2 );  

//Copy the folder to another folder. file1 is a subfolder of file2.
//Parameter 1: folder; parameter 2: folder
void copyDirectoryToDirectory( file1 , file2 );

//Copy folders with file filtering
void copyDirectory(File srcDir, File destDir, FileFilter filter)
  • Copy file
void copyFile(final File srcFile, final File destFile) //Copy files to another file

void long copyFile(final File input, final OutputStream output) //Copy files to output stream

void copyFileToDirectory( file1 , file2)  //Copy files to a specified directory

//Copy the contents of the input stream to the specified file
void copyInputStreamToFile( InputStream source, File destination)

//Copy the contents of the URL to a file. You can download files.
//Parameter 1: URL resource; parameter 2: target file
void copyURLToFile(final URL source, final File destination)

//Copy the contents of the URL to a file. You can download files.
//Parameter 1: URL resource; parameter 2: target file; parameter 3: http connection timeout; parameter 4: read timeout
void copyURLToFile(final URL source, final File destination,
                                     final int connectionTimeout, final int readTimeout)
                                     

Practical drill

  • Copy folders
package com.app;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class A1 {

    public static void main(String[] args) {
        String filePath1 = "F:/dd" ;
        File file1 = new File( filePath1 ) ;
        
        String filePath2 = "F:/ee" ;
        File file2 = new File( filePath2 ) ;
        
        try {
            //Copy folders
            FileUtils.copyDirectory( file1 , file2 );
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
  • Copy file
String filePath1 = "F:/123.gif" ;
String filePath2 = "F:/abc.gif" ;
        
File file1 = new File( filePath1 ) ;
File file2 = new File( filePath2 ) ;

//Copy file      
FileUtils.copyFile( file1 , file2);
  • Download the file copyURLToFile(final URL source, final File destination)
package com.app;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import org.apache.commons.io.FileUtils;

public class A8 {

    public static void main(String[] args) {
        String url = "http://imgsrc.baidu.com/baike/pic/item/7aec54e736d12f2ee289bffe4cc2d5628435689b.jpg" ;

        String filePath2 = "F:/abc.jpg" ;
        File file2 = new File( filePath2 ) ;

        try {

            //Download the image on the server to the abc.jpg image on the local F disk
            FileUtils.copyURLToFile( new URL( url ) , file2 );

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • Write strings to files
void writeStringToFile(final File file, final String data, final String encoding)

//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)
void writeStringToFile(final File file, final String data, final Charset encoding, final boolean
            append)

Small example

 package com.app;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

public class A8 {

    public static void main(String[] args) {
        String mes = "Get off work" ;

        String filePath2 = "F:/abc.xml" ;
        File file2 = new File( filePath2 ) ;

        try {
            FileUtils.writeStringToFile( file2 , mes , "UTF-8" , true ); 
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • Write byte arrays to files
//File: Target file
//Byte []: byte array
//boolean append: is it an additional mode
//final int off: where the array begins to write; final int len: the length of the write

void writeByteArrayToFile(final File file, final byte[] data)

void writeByteArrayToFile(final File file, final byte[] data, final boolean append)

void writeByteArrayToFile(final File file, final byte[] data, final int off, final int len)

void writeByteArrayToFile(final File file, final byte[] data, final int off, final int len,
                                            final boolean append)

Small example

package com.app;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

public class A8 {

    public static void main(String[] args) {
        String mes = "Haha, it's off duty." ;

        String filePath2 = "F:/abc.txt" ;
        File file2 = new File( filePath2 ) ;

        try {
            byte[] mesArray = mes.getBytes() ;
            FileUtils.writeByteArrayToFile( file2 , mesArray );
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • Write the contents of a collection to a file
//File file: Target file
//Collection<?> lines: Content collection
//boolean append: Is it an additional mode?
//String encoding: Encoding methods, such as "UTF-8" 
//String line Ending: What ends each line
void writeLines(final File file, final Collection<?> lines)

void writeLines(final File file, final Collection<?> lines, final boolean append)

void writeLines(final File file, final String encoding, final Collection<?> lines)

void writeLines(final File file, final String encoding, final Collection<?> lines,
                                  final boolean append)
                                  
void writeLines(final File file, final String encoding, final Collection<?> lines,
                                  final String lineEnding)

void writeLines(final File file, final String encoding, final Collection<?> lines,
                                  final String lineEnding, final boolean append)

void writeLines(final File file, final Collection<?> lines, final String lineEnding)

void writeLines(final File file, final Collection<?> lines, final String lineEnding,
                                  final boolean append)

Small example 1

package com.app;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.commons.io.FileUtils;

public class A8 {

    public static void main(String[] args) {
        
        ArrayList<String> list = new ArrayList<>() ;
        
        String mes = "Haha, it's off duty." ;
        String mes2 = "Go home, go home" ;
        
        list.add( mes ) ;  //First row of data
        list.add( mes2 ) ; //Second row of data

        String filePath2 = "F:/abc.txt" ;
        File file2 = new File( filePath2 ) ;

        try {
            FileUtils.writeLines( file2 , list );
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Result:

Small example 2

package com.app;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.commons.io.FileUtils;

public class A8 {

    public static void main(String[] args) {
        
        ArrayList<String> list = new ArrayList<>() ;
        
        String mes = "Haha, it's off duty." ;
        String mes2 = "Go home, go home" ;
        
        list.add( mes ) ;
        list.add( mes2 ) ;

        String filePath2 = "F:/abc.txt" ;
        File file2 = new File( filePath2 ) ;

        try {
            //For each line. Ending
            FileUtils.writeLines( file2 , list, ". ");
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Result:

  • Write in the document
/**
* Parameter interpretation
* File file: Target file
* CharSequence data :  What to write
* Charset encodingļ¼›String encoding :  Encoding format
* boolean append: Is it an additional mode?
*/

void write(final File file, final CharSequence data, final Charset encoding)

void write(final File file, final CharSequence data, final String encoding)

void write(final File file, final CharSequence data, final Charset encoding, final boolean append)

void write(final File file, final CharSequence data, final String encoding, final boolean append)

Small example

package com.app;
import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class A8 {

    public static void main(String[] args) {
            
        String mes = "Haha, it's off duty." ;
        
        String filePath2 = "F:/abc.txt" ;
        File file2 = new File( filePath2 ) ;

        try {
            FileUtils.write( file2 , mes , "utf-8" ,true );
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • file move
//Folder movement, all files including folders will be moved 
void moveDirectory(final File srcDir, final File destDir)

//The folder is moved inside another file. boolean createDestDir: If the destDir folder does not exist, do you want to create one
void moveDirectoryToDirectory(final File src, final File destDir, final boolean createDestDir)

//move file
void moveFile(final File srcFile, final File destFile)

//Move the file inside another file. boolean createDestDir: If the destDir folder does not exist, do you want to create one
void moveFileToDirectory(final File srcFile, final File destDir, final boolean createDestDir)

//Move files or directories to specified folders.
//boolean createDestDir: If the destDir folder does not exist, do you want to create one
void moveToDirectory(final File src, final File destDir, final boolean createDestDir)
  • Clear and delete folders
//Delete a folder, including all files in the folder and folder
void deleteDirectory(final File directory)

//Clear out all the contents of a folder
void cleanDirectory(final File directory)

//Deleting a file throws an exception
//If the file is a folder, delete all the contents of the folder and folder. If the file is a file, delete it.
//If a file/folder cannot be deleted for some reason, an exception is thrown
void forceDelete(final File file)  

//Delete a file without any exception thrown
//If the file is a folder, delete all the contents of the folder and folder. If the file is a file, delete it.
//If a file/folder cannot be deleted for some reason, no exception will be thrown
boolean deleteQuietly(final File file) 
  • create folder
//Create a folder and throw an exception if it cannot be created for some reason
//One-level or multi-level directories can be created at a time
void forceMkdir(final File directory)

//Create the parent directory of the file
void forceMkdirParent(final File file)

Small example 1

package com.app;
import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class A8 {

    public static void main(String[] args) {
            
        String filePath = "F:/123/abc/abc.txt" ;
        File file = new File( filePath ) ;
        
        try {
            //One-level or multi-level directories can be created at a time
            FileUtils.forceMkdir(file);
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Design sketch:

Small example 1

package com.app;
import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class A8 {

    public static void main(String[] args) {
            
        String filePath = "F:/123/abc/abc.txt" ;
        File file = new File( filePath ) ;
        
        try {
        //Create the parent directory of the file
        FileUtils.forceMkdirParent(file);
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Effect:

  • File access input/output stream
//Get the input stream
FileInputStream openInputStream(final File file)

//Get the output stream
FileOutputStream openOutputStream(final File file)
  • read 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 files into strings; String encoding: Encoding format
String readFileToString(final File file, final String encoding)

//Read the file into a set of strings; Charset encoding: Encoding format
List<String> readLines(final File file, final Charset encoding)

//Read files into a set of strings; String encoding: Encoding format
List<String> readLines(final File file, final String encoding)
  • Testing the modification time of two files which is newer/older
//Determine whether the modification of the file is newer than that of the reference file
boolean isFileNewer(final File file, final File reference) 

//Determine whether the modification of the file is newer than the date date date
boolean isFileNewer(final File file, final Date date)

//Determine whether the modification of the file file is newer than the timeMillis millisecond value
boolean isFileNewer(final File file, final long timeMillis) 

//Determine whether file modifications are older than reference files
boolean isFileOlder(final File file, final File reference)

//Determine whether the modification of the file is older than the date date date
boolean isFileOlder(final File file, final Date date)

//Determine whether the modification of the file file is older than the timeMillis millisecond value
boolean isFileOlder(final File file, final long timeMillis)
  • Other
//Determine whether a folder contains a file or folder
boolean directoryContains(final File directory, final File child)

//Get the size of a file or folder
long sizeOf(final File file) 

//Get temporary directory files
File getTempDirectory()

//Get the temporary directory path
String getTempDirectoryPath() 

//Get the user directory file  
File getUserDirectory()

//Get the user directory path  
static String getUserDirectoryPath()

//If it does not exist, create new files or create single-level or multi-level directories    
//Modify the file modification time if it exists   
void touch(final File file)

//Compare the contents of two files
boolean contentEquals(final File file1, final File file2)

Small example

package com.app;
import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class A8 {

    public static void main(String[] args) {
            
        String filePath = "F:/123" ;
        File file = new File( filePath ) ;
        
        File child = new File("F:/123/abc/123.txt") ;
        
        try {
            boolean hasChild = FileUtils.directoryContains( file , child) ;
            System.out.println( hasChild );
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Design sketch

Personal micro-signal: Zhaoyan jun125, welcome attention


Posted by Greg_BigPhpAmat on Wed, 19 Dec 2018 16:33:05 -0800