java ->IO流_commons類
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)
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
//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類