java ->IO流_commons類

來源:互聯網
上載者:User

標籤:cdir   操作   span   oid   targe   add   包含   項目   寫入   

commons-IO匯入classpath

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

1.建立lib檔案夾

2.將commons-io.jar拷貝到lib檔案夾

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

commons jar包下載

FilenameUtils類

這個工具類是用來處理檔案名稱(譯者註:包含檔案路徑)的,他可以輕鬆解決不同作業系統檔案名稱規範不同的問題

l  常用方法:

getExtension(String path):擷取檔案的副檔名;

getName():擷取檔案名稱;

isExtension(String fileName,String ext):判斷fileName是否是ext尾碼名;

FileUtils類

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

l  常用方法:

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

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

copyDirectoryToDirectory(File srcDir,File destDir);檔案夾複製

copyFile(File srcFile,File destFile);檔案複製

l  代碼示範:

/*

 * 完成檔案的複製

 */

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"));

    }

}

java ->IO流_commons類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.