html umlauts not renderd correctly if progamm executed via jar file

213 Views Asked by At

I have the following Java code to create an HTML file. I use the j2html library for that:

String html = html(
                     head(
                         meta().attr("charset", "UTF-8"),
                         title("test"),
                         link().withRel("stylesheet").withHref("style.css")
                     ),
                     body(
                            h1("Räte"),
                            h2("Äpfel")
                     )
                   ).render();
File file = new File("index.html");
FileUtils.writeStringToFile(file, html);

This works perfectly if I launch the program via IntelliJ, and I get this output:

test

Räte

Äpfel

But if I create a JAR artifact and launch it, the umlauts aren't displayed correctly. It looks like this:

test

R�te

�pfel

It's the same Java code and the charset is set to UTF-8.

1

There are 1 best solutions below

0
On

FileUtils.writeStringToFile(File, String) uses the JVM's default encoding when writing the string to the file.

The JVM's default encoding can differ depending on how you launch the JVM (that's why you've received different result from IntelliJ and direct JAR execution).

For this reason, the FileUtils.writeStringToFile(File, String) method is deprecated, and you should always use the FileUtils.writeStringToFile(File, String, Charset) method, where you specifify the encoding explicitly rather than relying on the JVM default:

FileUtils.writeStringToFile(file, html, StandardCharsets.UTF_8);