groovy 文件操作,對java原有的io進行了擴展,增加了許多閉包後省去了很多邏輯無關代碼,同時自動進行資源管理和異常處理。
讀取文件內容:
使用java代碼的基本寫法
FileInputStream fin = null;
try {
fin = new FileInputStream("test.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
// TODO: handle exception
} catch (IOException e) {
// TODO: handle exception
} finally {
try {
if (fin != null) {
fin.close();
}
}
catch (IOException e2) {
// TODO: handle exception
}
}
對一個文件進行讀取的時候,基本上都會用到上面的代碼,重複的寫這些代碼讓人感覺很枯燥,同時在閱讀 這樣的代碼的時候也極易干擾視線。真正要乾的事情也就是把文件內容輸出而已。
而在groovy中輸出文件的內容僅需要一行代碼
println new File("test.txt").text
代碼裏沒有流的出現,沒有資源關閉的出現,也沒有異常控制的出現,所有的這些groovy已經搞定了。
看到這樣的代碼是否有種清風拂面的感覺呢?呵呵!
下面介紹下groovy中File的一些接口:
1、對文件內容的操作
File file = new File('C:\\Users\\berdy\\Desktop\\test.txt')
//使用系統默認的編碼處理文件流
file.eachLine {println it }
//指定處理流的編碼
file.eachLine("utf8") {println it }
//指定文件內容行標的起始數字,默認爲1,根據需要設置爲其他數值
file.eachLine("utf8",10) {str,lineNumber->
println str
println lineNumber }
//對文件內容的每一行進行分割處理,比較常用在處理csv文件
file.splitEachLine(",") {println it }
//在閉包中定義過濾邏輯,對文件內容進行過濾處理
file.filterLine {String str->
if (str.contains('code'))
println str
}.writeTo(new PrintWriter(System.out))
file.append('hello world!')
//轉爲Writable對象,可重定向輸出
file.asWritable()
2、對目錄進行操作
File file = new File('.')
file.eachFileMatch(~/.*\.txt/) {File it-> println it.name } //使正則表達式匹配文件名
file.eachFileMatch(FILES, ~/.*\.txt/) { File it-> println it.name }
new File(".").eachFileRecurse {
println it.getPath();
}