commons-IO 工具類


一、導入classpath

加入classpath的第三方jar包內的class文件才能在項目中使用

創建lib文件夾

將commons-io.jar拷貝到lib文件夾

右鍵點擊commons-io.jar,Build Path→Add to Build Path

二、 FilenameUtils

這個工具類是用來處理文件名(譯者注:包含文件路徑)的,他可以輕松解決不同操作系統文件名稱規范不同的問題

常用方法:

getExtension(String path):獲取文件的擴展名;

getName(String filename):獲取文件名;

isExtension(String fileName,String ext):判斷fileName是否是ext后綴名;

三、FileUtils

提供文件操作(移動文件,讀取文件,檢查文件是否存在等等)的方法。

常用方法:

readFileToString(File file):讀取文件內容,並返回一個String;

writeStringToFile(File file,String content):將內容content寫入到file中;

copyDirectoryToDirectory(File srcDir,File destDir);文件夾復制

copyFile(File srcFile,File destFile);文件復制

四、代碼

/*
 * 完成文件的復制
 */
public class CommonsIODemo01 {
    public static void main(String[] args) throws IOException {
        //method1("D:\\test.avi", "D:\\copy.avi");
        
        //通過Commons-IO完成了文件復制的功能
        FileUtils.copyFile(new File("D:\\test.avi"), new File("D:\\copy.avi"));
    }

    //文件的復制
    private static void method1(String src, String dest) throws IOException {
        //1,指定數據源 
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));
        //2,指定目的地
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
        //3,讀
        byte[] buffer = new byte[1024];
        int len = -1;
        while ( (len = in.read(buffer)) != -1) {
            //4,寫
            out.write(buffer, 0, len);
        }
        //5,關閉流
        in.close();
        out.close();
    }
}

/*
 * 完成文件、文件夾的復制
 */
public class CommonsIODemo02 {
    public static void main(String[] args) throws IOException {
        //通過Commons-IO完成了文件復制的功能
        FileUtils.copyFile(new File("D:\\test.avi"), new File("D:\\copy.avi"));
        
        //通過Commons-IO完成了文件夾復制的功能
        //D:\基礎班 復制到 C:\\abc文件夾下
        FileUtils.copyDirectoryToDirectory(new File("D:\\基礎班"), new File("C:\\abc"));
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM