简体   繁体   中英

Java PrintWriter output looks weird in notepad

When I look at the file using mousepad on Linux, it looks correct. When I look at the file on Windows XP or Windows 7 with notepad, the output is all on the same line and is incorrect.

Here is the (correct) output for out.txt I'm getting on Linux:

  3.40        4.50        5.60
  3.40        4.50        5.60
  3.40        4.50        5.60 

EDIT: I encoded the text with CR+LF and it looks right, but how do I get java to export in that fashion?

Here's the code, it's just for testing this.

import java.io.*;
import java.util.*;
public class untitled {

    public static void main (String args[]) throws FileNotFoundException {      

        PrintWriter output = new PrintWriter("out.txt");

        double number1 = 3.4;
        double number2 = 4.5;
        double number3 = 5.6;

        for (int x=0; x<3; x++) {
        output.printf("%6.2f",number1);
        output.printf("%12.2f",number2);
        output.printf("%12.2f",number3);
        output.println("");
        }

        output.close();
    }
}

Thanks!

The reason it looks "weird" is because the Windows convention/standard for separating lines is Carriage Return, Line Feed ( "\\r\\n" ), as opposed to the *nix way of just a line feed ( "\\n" ). Therefore if you use a basic editor such as notepad, everything will seem to be on the same line. Better editors such as Notepad++, or even wordpad, will display the text file properly even if it's in *nix format.

If you run your Java program in Windows, the line separators will be set appropriately, however you can also change the line separator explicitly so that it is always "\\r\\n" by using System.setProperty() with the "line.separator" key.

If you do printf("%n"); Java will print the appropriate line separator for your 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