Dón*_*nal 488
String fileContents = new File('/path/to/file').text
Run Code Online (Sandbox Code Playgroud)
如果需要指定字符编码,请使用以下代码:
String fileContents = new File('/path/to/file').getText('UTF-8')
Run Code Online (Sandbox Code Playgroud)
小智 77
最短的路确实是公正的
String fileContents = new File('/path/to/file').text
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,您无法控制文件中的字节如何被解释为字符.AFAIK groovy试图通过查看文件内容来猜测编码.
如果需要特定的字符编码,可以使用指定字符集名称
String fileContents = new File('/path/to/file').getText('UTF-8')
Run Code Online (Sandbox Code Playgroud)
有关进一步参考,请参阅API文档File.getText(String).
小智 50
略有变化......
new File('/path/to/file').eachLine { line ->
println line
}
Run Code Online (Sandbox Code Playgroud)
P K*_*ers 10
在我的情况下new File()不起作用,它会导致FileNotFoundException在Jenkins管道作业中运行。下面的代码解决了这个问题,在我看来甚至更容易:
def fileContents = readFile "path/to/file"
Run Code Online (Sandbox Code Playgroud)
我仍然不完全了解这种区别,但是也许会对其他有同样麻烦的人有所帮助。可能是由于new File()在系统上创建了一个执行常规代码的文件而导致的异常,该文件与包含我要读取的文件的系统不同。
在这里您可以找到一些其他方法来执行相同的操作。
读取文件。
File file1 = new File("C:\Build\myfolder\myTestfile.txt");
def String yourData = file1.readLines();
Run Code Online (Sandbox Code Playgroud)
阅读完整文件。
File file1 = new File("C:\Build\myfolder\myfile.txt");
def String yourData= file1.getText();
Run Code Online (Sandbox Code Playgroud)
逐行读取文件。
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)
}
Run Code Online (Sandbox Code Playgroud)
创建一个新文件。
new File("C:\Temp\FileName.txt").createNewFile();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
234316 次 |
| 最近记录: |