【问题标题】:Writing with a PrintWriter to a file doesn't come out right使用 PrintWriter 写入文件不正确
【发布时间】:2015-01-20 09:07:57
【问题描述】:
public static void doubleSpace(String fileName) {
    try {
        FileReader reader = new FileReader(fileName);
        Scanner in = new Scanner(reader);
        String outputFileName = fileName.charAt(0) + ".ds";
        PrintWriter pOut = new PrintWriter(outputFileName);
        // Opening of files for input and output
        while (in.hasNextLine()) {
            String line = in.nextLine();
            pOut.println(line + "\n");
            pOut.print("\n");
            // System.out.println(line + "\n"); //Test
        }
        pOut.close(); // Close the files if they have been opened.

    } catch (Exception e) {

    }
}

所以基本上我的输入文件包含

a
b
c

我的输出文件应该是这样的

a

b

c

但是,我的输出文件始终只包含abc

任何帮助将不胜感激!

【问题讨论】:

  • 你的程序在我的电脑上运行良好。检查是否引发任何异常
  • 那么,你想将换行符加倍?
  • 您是否使用记事本在 Windows 中打开文件? "\n" 只是一个换行符,但对于记事本,你只会看到换行,而行以 "\r\n" 结尾。尝试使用其他文本编辑器打开文件。
  • 单个pOut.println(line + "\n"); 就足够了,因为println 以换行符加上\n 结束字符串。

标签: java output printwriter


【解决方案1】:

使用BufferedWriter。它有一个.newLine() 方法。此方法将使用平台的默认行分隔符。

并使用BufferedReader。它有一个.readLine() 方法。

例子:

// NOTE: you should really be using UTF-8
final Charset charset = Charset.defaultCharset();

final Path src = Paths.get(filename);
final Path dst = Paths.get(filename + ".ds");

String line;

try (
    final BufferedReader reader = Files.newBufferedReader(src, charset);
    final BufferedWriter writer = Files.newBufferedWriter(dst, charset);
) {
    while ((line = reader.readLine()) != null) {
        writer.write(line);
        writer.newLine();
        writer.newLine();
    }
}

【讨论】:

    【解决方案2】:

    您可能在平台的换行符中使用了错误的字符。使用

    System.getProperty("line.separator");
    

    获取正确的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      相关资源
      最近更新 更多