简体   繁体   中英

Does Java MessageFormat have a platform lineseparator like String.format does?

This is a long shot, but I'm hoping to replace the newline literals in MessageFormat code like

LOG.log(INFO, "message={0}\nAnd extra blank line\n", new String[]{message});

with a platform-independent pattern. The String.format() pattern %n does not work for Logger or MessageFormat. I'd like to avoid passing System.lineseperator as an argument like this:

LOG.log(INFO, "message={0}{1}And a blank line{1}",new String[]{message, System.lineSeparator()});

I don't see any mention of newline or lineseparator in the docs for MessageFormat, but perhaps it is mentioned somewhere else. https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/MessageFormat.html

Does Java MessageFormat have a platform lineseparator like String.format does?

According to my reading of the code, the answer is No.

And there aren't any extant RFEs or Bug reports about this that I can see in the Java or OpenJDK Bug trackers 1 .

However, as Joop notes, since you are actually asking this in the context of logging, there are a few other ways to solve this (though not all will be practical):

  • Ignore the problem. These messages are are going into log files. It doesn't really matter. (OK... maybe it complicates log viewing and searching.)
  • Create a custom subclass of MessageFormat that recognizes a syntax that means "platform specific line separator".
  • Handle the line separators by translating them in a custom log message appender or formatter; eg
    • Translate all line separators of the "wrong kind".
    • Recognize and translate a magic character sequence...
  • Change to a different logging framework that uses java.util.Formatter for message construction. AFAIK, most modern frameworks do.

1 - You could read that as "evidence" of how little use there is of MessageFormat in real world / modern applications, or how few people use it in contexts where line separators matter.


@Bohemian asked:

Why do you want to avoid "passing System.lineseparator as an argument"?

I would have thought that was self-evident. It is clunky.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM