簡體   English   中英

如何將 Groovy 中的文件讀入字符串?

[英]How to read a file in Groovy into a string?

我需要從文件系統中讀取一個文件並將整個內容加載到 groovy 控制器中的字符串中,最簡單的方法是什么?

String fileContents = new File('/path/to/file').text

如果您需要指定字符編碼,請改用以下內容:

String fileContents = new File('/path/to/file').getText('UTF-8')

最短的路確實只是

String fileContents = new File('/path/to/file').text

但在這種情況下,您無法控制文件中的字節如何解釋為字符。 AFAIK groovy 試圖通過查看文件內容來猜測這里的編碼。

如果你想要一個特定的字符編碼,你可以指定一個字符集名稱

String fileContents = new File('/path/to/file').getText('UTF-8')

如需進一步參考,請參閱File.getText(String)上的 API 文檔

一個細微的變化...

new File('/path/to/file').eachLine { line ->
  println line
}

在我的情況下, new File()不起作用,它在 Jenkins 管道作業中運行時會導致FileNotFoundException 以下代碼解決了這個問題,在我看來更容易:

def fileContents = readFile "path/to/file"

我仍然不完全理解這種差異,但也許它會幫助其他有同樣問題的人。 異常可能是因為new File()在執行常規代碼的系統上創建了一個文件,該文件與包含我想要讀取的文件的系統不同。

最簡單的方法是

new File(filename).getText()

這意味着你可以這樣做:

new File(filename).text

在這里你可以找到一些其他的方法來做同樣的事情。

讀取文件。

File file1 = new File("C:\Build\myfolder\myTestfile.txt");
def String yourData = file1.readLines();

讀取完整文件。

File file1 = new File("C:\Build\myfolder\myfile.txt");
def String yourData= file1.getText();

讀取文件行再見行。

File file1 = new File("C:\Build\myfolder\myTestfile.txt");
for (def i=0;i<=30;i++) // specify how many line need to read eg.. 30
{
 log.info file1.readLines().get(i)

}

創建一個新文件。

new File("C:\Temp\FileName.txt").createNewFile();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM