Jenkins Pipeline: How to write UTF-8 files using writeFile?

I hope this is not a mistake, and I'm just doing something wrong. I have a Jenkins pipeline job (v2.19.1), and in it groovy script I need to find and replace the text in an existing text file on a Windows node.

I used fart.exe and powershell to find and replace, but I really would like to do this with just groovy in Jenkins and eliminate the dependency on fart / powershell / etc. and make this code more reusable for both Linux and windows.

After long searches and attempts at various approaches, the closest I got was the use of readFile and writeFile. However, I could not get writeFile to create the UTF-8 file. It creates an ANSI file even when I specify UTF-8 (if I do it correctly).

Here is what I still have ...

def fileContents = readFile file: "test.txt", encoding: "UTF-8" fileContents = fileContents.replace("hello", "world") echo fileContents writeFile file: "test.txt", text: fileContents, encoding: "UTF-8" 

I have confirmed with several text editors that the test.txt file is UTF-8 when I run, and ANSI after the writeFile line. I tried all inclusion / absence combinations, including the encoding property, and "utf-8" versus "UTF-8". But in all cases, the file is written as ANSI (as reported by both Notepad ++ and VS Code). In addition, a question mark (HEX 3F) is added as the very first character of the file.

The extra 3F character is not displayed in the echo line, so the problem is in the writeFile line.

+5
source share
1 answer

you can do it in pure groovy just using

 def file = new File('test.txt') def fileContents = file.getText('UTF-8') fileContents = fileContents.replace("hello", "world") file.setText(fileContents, 'UTF-8') 
0
source

Source: https://habr.com/ru/post/1264629/


All Articles