標籤: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類