一、commons-IO概述
Commons IO是針對(duì)開發(fā)IO流功能的工具類庫(kù)客情,必須導(dǎo)入第三方j(luò)ar包才能使用其弊。
主要包括六個(gè)區(qū)域:
工具類——使用靜態(tài)方法執(zhí)行共同任務(wù)
輸入——用于InputStream和Reader實(shí)現(xiàn)
輸出——用于OutputStream和Writer實(shí)現(xiàn)
過濾器——各種文件過濾器實(shí)現(xiàn)
比較器——各種文件的java.util.Comparator實(shí)現(xiàn)
文件監(jiān)聽器——監(jiān)聽文件系統(tǒng)事件的組件
二癞己、FilenameUtils
這個(gè)工具類是用來處理文件名(譯者注:包含文件路徑)的,他可以輕松解決不同操作系統(tǒng)文件名稱規(guī)范不同的問題梭伐。
常用方法:
- getExtension(String path):獲取文件的擴(kuò)展名痹雅;
- getName():獲取文件名;
- isExtension(String fileName,String ext):判斷fileName是否是ext后綴名糊识;
三绩社、FileUtils
提供文件操作(移動(dòng)文件,讀取文件赂苗,檢查文件是否存在等等)的方法愉耙。
常用方法:
- readFileToString(File file):讀取文件內(nèi)容,并返回一個(gè)String拌滋;
- writeStringToFile(File file朴沿,String content):將內(nèi)容content寫入到file中;
- copyDirectoryToDirectory(File srcDir,File destDir);文件夾復(fù)制
- copyFile(File srcFile, File destFile): 文件復(fù)制
實(shí)例:文件復(fù)制
- 普通方式
/*
* 普通方式败砂,完成文件的復(fù)制
*/
public class CommonsIODemo01 {
public static void main(String[] args) throws IOException {
//method1("D:\\test.avi", "D:\\copy.avi");
//通過Commons-IO完成了文件復(fù)制的功能
FileUtils.copyFile(new File("D:\\test.avi"), new File("D:\\copy.avi"));
}
//文件的復(fù)制
private static void method1(String src, String dest) throws IOException {
//1,指定數(shù)據(jù)源
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,關(guān)閉流
in.close();
out.close();
}
}
- commons-io完成文件吠卷、文件夾的復(fù)制
/*
* 使用commons-io完成文件锡垄、文件夾的復(fù)制
*/
public class CommonsIODemo02 {
public static void main(String[] args) throws IOException {
//通過Commons-IO完成了文件復(fù)制的功能
FileUtils.copyFile(new File("D:\\test.avi"), new File("D:\\copy.avi"));
//通過Commons-IO完成了文件夾復(fù)制的功能
//D:\基礎(chǔ)班 復(fù)制到 C:\\abc文件夾下
FileUtils.copyDirectoryToDirectory(new File("D:\\基礎(chǔ)班"), new File("C:\\abc"));
}
}
三、IOUtils
IOUtils包含處理讀祭隔、寫和復(fù)制的工具方法货岭。方法對(duì)InputStream、OutputStream疾渴、Reader和Writer起作用千贯。
實(shí)例:從一個(gè)URL讀取字節(jié)的任務(wù),并且打印它們:
- 普通方式
InputStream in = new URL( "http://commons.apache.org" ).openStream();
try {
InputStreamReader inR = new InputStreamReader( in );
BufferedReader buf = new BufferedReader( inR );
String line;
while ( ( line = buf.readLine() ) != null ) {
System.out.println( line );
}
} finally {
in.close();
}
- 使用IOUtils
InputStream in = new URL( "http://commons.apache.org" ).openStream();
try {
System.out.println(IOUtils.toString(in));
} finally {
IOUtils.closeQuietly(in);
}