- 一:Java 与 Groovy 读文件操作比较
Groovy 对 java.io.File 进行了扩展,增加了一些接受闭包参数和简化文件操作的方法。作为对比,我们还是先来看看 java 中读取文件的两种常方法,分别是行读取和字节缓冲区读取:1//--BufferedReader 行读取 2BufferedReader br = null; 3try { 4 br = new BufferedReader(new FileReader("foo.txt")); 5 List<String> content = new ArrayList<String>(); 6 String line = null; 7 while((line=br.readLine())!=null){ 8 content.add(line); 9 } 10} catch (FileNotFoundException e) { 11} catch(IOException e){ 12} finally{ 13 if(br != null){ 14 try { 15 br.close(); 16 } catch (IOException e) { 17 } 18 } 19}1//--借助于 buffer 缓冲区来读字节 2InputStream is = null; 3try { 4 is = new FileInputStream("foo.txt"); 5 StringBuffer content = new StringBuffer(); 6 int read = -1; 7 byte[] buffer = new byte[1024]; 8 while((read=is.read(buffer))!=-1){ 9 content.append(new String(buffer,0,read)); 10 } 11} catch (FileNotFoundException e) { 12} catch(IOException e){ 13} finally{ 14 if(is != null){ 15 try { 16 is.close(); 17 } catch (IOException e) { 18 } 19 } 20}
从上面可看到,采用 Java 传统方式来读取文件内容,不仅代码行多,而且还必须自己用 try/catch/finally 来处理异常和资源的关闭。现在马上来看看 Groovy 完成以上工作的代码是怎么的,只要一行代码: Read More