Groovy讀取文件信息


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

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

 

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

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

 

3. splitEachLine -- 讀取文件的每一行,然后對行以指定分隔符分割成數組。不用再多說了,這個方法對處理 CSV 文件那可是相當的高效。

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() 方法了

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

 

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

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 -- 以深度優先的方式遞歸遍歷路徑,列出文件(包括目錄),傳給閉包處理

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() 等等。還要留意一下有一些方法是可以指定字符集的。

 

----

操作目錄

列出目錄所有文件(包含子文件夾,子文件夾內文件) :

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"
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM