Skip to content
Advertisement

Properly set UTF-8 encoding to a FileHandler in Java

I initialize my FileHandler as follows:

private Handler initializeFileHandler() {
    LogManager.getLogManager().reset();
    Handler handler = null;
    try {
        Files.deleteIfExists(Paths.get(logPath));
        handler = new FileHandler(logPath);
        handler.setLevel(Level.FINER);
        handler.setEncoding(StandardCharsets.UTF_8.name());
        handler.setFormatter(new Formatter() {
            @Override
            public String format(LogRecord record) {
                return String.format(
                        "%s: Class: %s; Type: %s; %s%s",
                        formatter.format(LocalDateTime.now()),
                        record.getLoggerName(),
                        record.getLevel(),
                        record.getMessage(),
                        System.lineSeparator()
                );
            }
        });
    } catch (IOException ex) {
        //noinspection UseOfSystemOutOrSystemErr
        System.err.println("Fehler beim initialisieren vom FileHandler");
        //noinspection CallToPrintStackTrace
        ex.printStackTrace();
        //noinspection CallToSystemExit
        System.exit(1);
    }
    return handler;
}

and add it to my Logger like this:

public ConcurrentLogger initializeLogger(ConcurrentLogger logger) {
    logger.addHandler(fileHandler);

    Handler handler = new ConsoleHandler();
    handler.setLevel(Level.FINER);
    logger.addHandler(handler);

    logger.setLevel(Level.ALL);
    return logger;
}

If i remove the setEncoding on my FileHandler, its sill is wrong. But strangely, if i add the exact same Encoding to my ConsoleHandler, it stops working too. (But without the explicit set, it works at least in my IntelliJ-Console). IntelliJ-Console WITHOUT the explicit encoding (same code as above):

 INFORMATION: BruteForce wird planmäßig beendet.

Ouput in the .log File:

INFORMATION: BruteForce wird planmäßig beendet.

It looks same in Notepad++ and IntelliJ. How do i set the UTF-8 Encoding Properly? Notepad++ show the File is encoded in UTF-8, but still looks broken. (Btw. it doesnt Matter if i use .toString() or name() on the UTF_8 Instance)

Advertisement

Answer

IntelliJ shows the File-Encoding in the lower right. On the affected Class it shows “UTF-8”, so thats correct.

But i found in the Settings in “Editor->File Encodings” two Settings called “Global Encoding” and “Project Encoding”. The first was already UTF-8, the latter ISO8859_1. I changed that and the Output-File works as intended now, with proper encoding. I just needed to add the Encoding to the ConsoleHandler now too, cause that was broken now.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement