Robert Strauch
Robert Strauch

Reputation: 12896

Groovy script does not write file as UTF-8

I have the following piece of code:

def f = new File("test.txt")
f.write("test", "UTF-8")

When opening the file in Notepad++ (or any other editor) it is still in ISO-8859-1 instead of UTF-8. Opening the file in a hex editor it does not contain the "magic bytes" 0xEFBBBF.

Regards,
Robert

Upvotes: 2

Views: 9962

Answers (2)

A Goldstein
A Goldstein

Reputation: 21

Remember, Groovy is based on Java. Just write:

File outFile = new File(filePath)
Writer out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(outFile), "UTF8"));
out.append(strBuf.toString())
out.flush()
out.close()

Upvotes: 0

buruzaemon
buruzaemon

Reputation: 3907

UTF-8 files do not really require the Byte-Order Mark indicator.

For example, if your UTF-8 file only contains ASCII chars, the file utility will return this:

$ file [filename]
ASCII text

But when you introduce, say, Japanese chars into that file, then file will return this:

UTF-8 Unicode text

.. but the file will not begin with the BOM.

Upvotes: 4

Related Questions