What's up with Java's “%n” in printf?

2019-01-03 05:39发布

I'm reading Effective Java and it uses %n for the newline character everywhere. I have used \n rather successfully for newline in Java programs.

Which is the 'correct' one? What's wrong with \n ? Why did Java change this C convention?

8条回答
家丑人穷心不美
2楼-- · 2019-01-03 06:15

Notice these answers are only true when using System.out.printf() or System.out.format() or the Formatter object. If you use %n in System.out.println(), it will simply produce a %n, not a newline.

查看更多
Luminary・发光体
3楼-- · 2019-01-03 06:16

%n is portable accross platforms \n is not.

See the formatting string syntax in the reference documentation:

'n' line separator The result is the platform-specific line separator

查看更多
Ridiculous、
4楼-- · 2019-01-03 06:20

From a quick google:

There is also one specifier that doesn't correspond to an argument. It is "%n" which outputs a line break. A "\n" can also be used in some cases, but since "%n" always outputs the correct platform-specific line separator, it is portable across platforms whereas"\n" is not.

Please refer https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

Original source

查看更多
别忘想泡老子
5楼-- · 2019-01-03 06:23

In java, \n always generate \u000A linefeed character. To get correct line separator for particular platform use %n.

So use \n when you are sure that you need \u000A linefeed character, for example in networking.
In all other situations use %n

查看更多
何必那么认真
6楼-- · 2019-01-03 06:28

"correct" depends on what exactly it is you are trying to do.

\n will always give you a "unix style" line ending. \r\n will always give you a "dos style" line ending. %n will give you the line ending for the platform you are running on

C handles this differently. You can choose to open a file in either "text" or "binary" mode. If you open the file in binary mode \n will give you a "unix style" line ending and "\r\n" will give you a "dos style" line ending. If you open the file in "text" mode on a dos/windows system then when you write \n the file handling code converts it to \r\n. So by opening a file in text mode and using \n you get the platform specific line ending.

I can see why the designers of java didn't want to replicate C's hacky ideas regarding "text" and "binary" file modes.

查看更多
Viruses.
7楼-- · 2019-01-03 06:34

While \n is the correct newline character for Unix-based systems, other systems may use different characters to represent the end of a line. In particular, Windows system use \r\n, and early MacOS systems used \r.

By using %n in your format string, you tell Java to use the value returned by System.getProperty("line.separator"), which is the line separator for the current system.

查看更多
登录 后发表回答