How to read a file in Groovy into a string?

前端 未结 6 1335
不知归路
不知归路 2020-12-02 05:12

I need to read a file from the file system and load the entire contents into a string in a groovy controller, what\'s the easiest way to do that?

相关标签:
6条回答
  • 2020-12-02 05:56

    the easiest way would be

    new File(filename).getText()

    which means you could just do:

    new File(filename).text

    0 讨论(0)
  • 2020-12-02 06:04

    The shortest way is indeed just

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

    but in this case you have no control on how the bytes in the file are interpreted as characters. AFAIK groovy tries to guess the encoding here by looking at the file content.

    If you want a specific character encoding you can specify a charset name with

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

    See API docs on File.getText(String) for further reference.

    0 讨论(0)
  • 2020-12-02 06:09

    Here you can Find some other way to do the same.

    Read file.

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

    Read Full file.

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

    Read file Line Bye Line.

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

    Create a new file.

    new File("C:\Temp\FileName.txt").createNewFile();
    
    0 讨论(0)
  • 2020-12-02 06:10

    In my case new File() doesn't work, it causes a FileNotFoundException when run in a Jenkins pipeline job. The following code solved this, and is even easier in my opinion:

    def fileContents = readFile "path/to/file"
    

    I still don't understand this difference completely, but maybe it'll help anyone else with the same trouble. Possibly the exception was caused because new File() creates a file on the system which executes the groovy code, which was a different system than the one that contains the file I wanted to read.

    0 讨论(0)
  • 2020-12-02 06:12
    String fileContents = new File('/path/to/file').text
    

    If you need to specify the character encoding, use the following instead:

    String fileContents = new File('/path/to/file').getText('UTF-8')
    
    0 讨论(0)
  • 2020-12-02 06:14

    A slight variation...

    new File('/path/to/file').eachLine { line ->
      println line
    }
    
    0 讨论(0)
提交回复
热议问题