Groovy讀取文件信息

1. eachLine -- 打開和讀取文件的每一行html

new File("foo.txt").eachLine {
    println it.toUpperCase();
}

 

2. readLines -- 其做用基本與 eachLine 相同,但它不接受閉包爲參數,而是把文件行讀到一個 List 中java

lineList = new File("foo.txt").readLines();
lineList.each {
    println it.toUpperCase();
}

 

3. splitEachLine -- 讀取文件的每一行,而後對行以指定分隔符分割成數組。不用再多說了,這個方法對處理 CSV 文件那但是至關的高效。linux

lineList = new File("foo.csv").splitEachLine(",") {
    println "name=${it[0]} balance=${it[1]}";
}

 

4. eachByte -- 處理二進制文件,以字節級訪問文件,這個方法至關於 eachLine() 方法。正則表達式

new File("foo.bin").eachByte { print it; }

 

5. readBytes -- 天然,處理二進制文件,以字節級訪問文件,這個方法至關於 readLines() 方法了express

byteList = new File("foo.bin").readBytes();
byteList.each {
    println it;
}

 

6. write -- Groovy 用這個方法寫文件真是太直觀了windows

new File("foo.txt").write("testing testing");

new File("foo.txt").write("""
This is
just a test file
to play with
""");

 

以上使用了三重引用語法,其中的文本保留格式的寫入到文件中。注意上面寫法在文件首尾都會有一個空行,除非起始和結束字符都要緊貼 """;還有上面方法寫的文件用詞本打開會是擠在一行,用 editplus 打開是多行,由於它採用的是 linux 下的 /n 換行,而不是 windows 下的 /r/n 換行。、

7. append -- 與 write 覆寫文件不一樣,append 是在文件後追加內容數組

new File("foo.txt").append("""/
This is  
just a test file  
to play withff
"""  
);

 

8. eachFile -- 功能上相似 java.io.File 的 listFiles() 方法。用來列舉路徑中的每一個文件(包括目錄),傳給閉包處理閉包

new File(".").eachFile {   //這裏的 File 表示的是一個路徑
    println it.getName();  //eachFile() 列出的每一項是一個 File 實例
}

 

9. eachFileRecurse -- 以深度優先的方式遞歸遍歷路徑,列出文件(包括目錄),傳給閉包處理app

new File(".").eachFileRecurse {   //這裏的 File 表示的是一個路徑
    println it.getPath();  //eachFile() 列出的每一項是一個 File 實例
}

 


10. …… 再重複一下,其餘 Groovy 對 java.io.File 的擴展方法請參考 http://groovy.codehaus.org/groovy-jdk/java/io/File.html。 如 eachDir()、eachDirMatch()、eachDirRecurse()、eachFileMatch()、filterLine()、 newInputStream()、newOutputStream()、newReader()、newPrintWriter()、 withInputStream()、withOutputStream()、withReader()、withPrintWriter() 等等。還要留意一下有一些方法是能夠指定字符集的。spa

 

----

操做目錄

列出目錄全部文件(包含子文件夾,子文件夾內文件) :

def dir = new File(dirName)  
if (dir.isDirectory()) {  
    dir.eachFileRecurse { file ->  
        println file  
    }  
} 

dir.eachFileMatch(~/.*\.txt/) {File it-> println it.name  } //使正則表達式匹配文件名  
dir.eachFileMatch(FILES, ~/.*\.txt/) { File it-> println it.name  }   

 

 

寫文件

import java.io.File  
  
def writeFile(fileName) {  
    def file = new File(fileName)  
      
    if (file.exists())   
        file.delete()  
          
    def printWriter = file.newPrintWriter() //   
      
    printWriter.write('The first content of file')  
    printWriter.write('\n')  
    printWriter.write('The first content of file')  
      
    printWriter.flush()  
    printWriter.close()  
}  

 

除了 file.newPrintWriter() 能夠獲得一個 PrintWriter,相似方法還有 file.newInputStream()
file.newObjectInputStream()等。

更簡潔寫法:

new File(fileName).withPrintWriter { printWriter ->  
     printWriter.println('The first content of file')  
}  

 

解析 xml 文件

<?xml version="1.0" encoding="UTF-8"?> 
<customers> 
  <corporate> 
    <customer name="bill gates" company="microsoft"></customer> 
    <customer name="steve jobs" company="apple"></customer> 
    <customer name="bill dyh" company="sun"></customer> 
  </corporate> 
  <consumer> 
    <customer name="jone Doe"></customer> 
    <customer name="jane Doe"></customer>    
  </consumer> 
</customers>

 

def customers = new XmlSlurper().parse(new File("customers.xml")) 
/*對文件進行解析*/ 
for(customer in customers.corporate.customer){ 
    println "${customer.@name} works for${customer.@company}"; 
} 

 

解析 propeties 文件

參考 groovy: How to access to properties file?,代碼以下:

def props = new Properties()
new File("message.properties").withInputStream { 
  stream -> props.load(stream) 
}
// accessing the property from Properties object using Groovy's map notation
println "capacity.created=" + props["capacity.created"]

def config = new ConfigSlurper().parse(props)
// accessing the property from ConfigSlurper object using GPath expression
println "capacity.created=" + config.capacity.created

 

另一種方式:

def config = new ConfigSlurper().parse(new File("message.groovy").toURL())

 

message.groovy 內容以下:

capacity {
  created="x"
  modified="y"
}
相關文章
相關標籤/搜索