How to read a file in Groovy into a string?

前端 未结 6 1368
不知归路
不知归路 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 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.

提交回复
热议问题