Java PrintWriter 输出在记事本中看起来很奇怪 [英] Java PrintWriter output looks weird in notepad

查看:45
本文介绍了Java PrintWriter 输出在记事本中看起来很奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 Linux 上使用鼠标垫查看文件时,它看起来是正确的.当我用记事本在 Windows XP 或 Windows 7 上查看文件时,输出都在同一行并且不正确.

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.

这是我在 Linux 上得到的 out.txt 的(正确)输出:

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 

我用 CR+LF 对文本进行了编码,看起来不错,但是如何让 java 以这种方式导出?

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();
    }
}

谢谢!

推荐答案

它看起来怪异"的原因是因为 Windows 用于分隔行的约定/标准是 Carriage Return, Line Feed ("\r\n"),而不是仅换行的 *nix 方式 ("\n").因此,如果您使用记事本等基本编辑器,一切似乎都在同一行上.更好的编辑器,例如 Notepad++,甚至写字板,即使是 *nix 格式也能正确显示文本文件.

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.

如果您在 Windows 中运行 Java 程序,行分隔符将被适当设置,但是您也可以通过使用 "\r\n" 显式更改行分隔符,使其始终为 "\r\n"a href="http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html" rel="nofollow">System.setProperty() 和 "line.separator" 键.

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.

这篇关于Java PrintWriter 输出在记事本中看起来很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆