【问题标题】:FileWriter won't append new linesFileWriter 不会追加新行
【发布时间】:2016-04-23 23:46:03
【问题描述】:

我不确定为什么我的输出函数在创建文件时没有选择换行符。代码如下:

private void outputToFile(){
    final JFileChooser fc = new JFileChooser();
    fc.setSelectedFile(new File("frequency.txt"));
    int returnVal = fc.showSaveDialog(null);
    File file = fc.getSelectedFile();
    try{
      FileWriter writer = new FileWriter(file);
      String out = this.toString();
      writer.append(out);
      writer.flush();
      writer.close();
    }
    catch(IOException e){
      System.out.println("Cancelled and aborted");
    }
  }

当我打印到命令行时,我的 toString 方法工作正常,但在文件输出中删除了 \n 的所有实例。这是此函数的“损坏”输出示例(这是一个频率计数器)

输出文件: 问:5 \n: 7 C: 1 一个:5 时间:6 年代:3 (空格):6 r: 1 e: 4 三:1 ○:2 升:3 .: 2 宽:1 ,: 1 小时:4 ':1 w: 1 是:3 \t: 1 回复:1 我:1 克:1 ?: 1 乙:1 !: 1

每个数字之后应该有新行。

如果你想要我的全部课程,这里是:http://pastebin.com/CCLLBUqF

【问题讨论】:

    标签: java newline jfilechooser filewriter swingx


    【解决方案1】:

    在编写文件时,您需要同时包含换行符和换行符。 因此,在您的 toString() 方法中,添加 "\n" 换行符,而不是添加换行符和换行符:"\r\n"

    【讨论】:

    • 理想情况下你应该使用 System.getProperty("line.separator");而不是依赖于平台的行分隔符
    • 嗯。我尝试同时使用 "\r" 和 System.getproperty 方法,但都失败了。 \r 没有改变任何东西,System.getProperty 只是在各处添加了“null”。
    • 没关系。当我将其更改为使用 \r\n 的顺序时,它起作用了。非常感谢!
    • 行终止符是\n、\r 或\r\n。不是您在此处显示的内容。
    猜你喜欢
    • 2015-08-24
    • 2018-06-18
    • 2011-08-02
    • 1970-01-01
    • 2016-12-25
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多