Using line break "\ n" in Java

11

What problem can a Java programmer have when using "\n" to skip line?

Note: I have already used it for N reasons, writing a file TXT and others.

    
asked by anonymous 26.02.2014 / 19:03

5 answers

14

The only problem is that if your file is opened in Windows (or Mac), some text editors will not recognize the line break and display everything as one line. If you want to ensure line breaks are in the format of your current system, it's best to use the property % system%:

String quebraLinha = System.getProperty("line.separator"); // "\n" no Linux, 
                                                           // "\r\n" no Windows
                                                           // "\r" em algumas versões do Mac
    
26.02.2014 / 19:10
15

Not every platform uses "\n" as a line separator. Example:

Linux: "\n"
Windows: "\r\n"
Some Macs: "\r"

So one way of knowing which line separator for the current platform is this:

System.getProperty("line.separator"); // Anterior ao Java 7
System.lineSeparator();               // A partir do Java 7

Source: link

    
26.02.2014 / 19:12
4

This question already has some very interesting answers, but I understand that the question is not about how to use the line break but about the possible problems.

Well, I'll mention two that I've been through:

  • When importing / exporting text files from / to other systems, you should set an OS-independent standard to avoid incompatibilities.

Lesson: In web systems, we can not rely on system ownership .

The solution in most of these cases is to leave the hard-coded break in the code.

Personally, I'd rather leave System.getProperty("line.separator") because it works on Windows, the system that most users use. Linux and Mac users often use more advanced editors that would recognize the different line breaks of the OS.

    
26.02.2014 / 19:51
3

As others have said, it is not all systems that interpret End Of Line equally. For example, since my hosts file on Windows had, in one way or another, been saved with \n and not \r\n . What happened was that Windows could not understand the file and made no entry of the file recognized (by ping , etc.).

    
26.02.2014 / 19:19
2

In the case of PHP, we have a constant PHP_EOL which means line break, because for some systems the right thing is to break lines with \r\n and in other systems it is simply \n .

For Perl, there is the say method that is nothing more than a echo with a line break at the end. I believe that the line break character, in this case, also varies from system to system (although Perl is a language designed to work mostly on UNIX systems).

Java probably has some character or workaround so you do not have to directly use \n or \r\n .

    
26.02.2014 / 19:08