简体   繁体   中英

java - Line breaks not working

I'm writing a simple program that writes data to the selected file .
everything is going great except the line breaks \\n the string is written in the file but without line breaks

I've tried \\n and \\n\\r but nothing changed
the program :

    public void prepare(){
    String content = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n\r<data>\n\r<user><username>root</username><password>root</password></user>\n\r</data>";
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(file);
    } catch (FileNotFoundException ex) {
        System.out.println("File Not Found .. prepare()");
    }
    byte b[] = content.getBytes();
    try {
        fos.write(b);
        fos.close();
    } catch (IOException ex) {
        System.out.println("IOException .. prepare()");
    }
}
public static void main(String args[]){
    File f = new File("D:\\test.xml");
    Database data = new Database(f);
    data.prepare();
}

Line endings for Windows follow the form \\r\\n , not \\n\\r . However, you may want to use platform-dependent line endings. To determine the standard line endings for the current platform, you can use:

System.lineSeparator()

...if you are running Java 7 or later. On earlier versions, use:

System.getProperty("line.separator")

My guess is that you're using Windows. Write \\r\\n instead of \\n\\r - as \\r\\n is the linebreak on Windows.

I'm sure you'll find that the characters you're writing into the file are there - but you need to understand that different platforms use different default line breaks... and different clients will handle things differently. (Notepad on Windows only understands \\r\\n , other text editors may be smarter.)

The correct linebreak sequence on windows is \\r\\n not \\n\\r .

Also your viewer may interpret them differently. For example, notepad will only display CRLF linebreaks, but Write or Word have no problem displaying CR or LF alone.

You should use System.lineSeparator() if you want to find the linebreak sequence for the current platform. You are correct in writing them explicitly if you are attempting to force a linebreak format regardless of the current platform.

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