【问题标题】:How can I make a line break when writing a string to a file?将字符串写入文件时如何换行?
【发布时间】:2019-09-23 11:43:40
【问题描述】:

我想将文本写入文件,每次我这样做时都应该换行。我已经看到这个问题的许多答案只是“使用 \n”,但这对我不起作用。

这是我使用的代码:

File file = new File("C:\\Users\\Schule\\IdeaProjects\\projectX\\src\\experiment\\input.txt");
        boolean result;
        if(!file.exists()) {
            try {
                // create a new file
                result = file.createNewFile();
                // test if successfully created a new file
                if(result) {
                    System.out.println("Successfully created " + file.getCanonicalPath());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String output = name + ": " + highscoreString + "\n";
        try {
            PrintWriter out = new PrintWriter(new FileWriter(file, true));
            out.append(output);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

我的代码将新的高分和创造它的人的名字写在一个文件中。它工作得很好,除了它将所有内容写在这样的一行上,例如: 尼古拉:你的高分是 10 秒托马斯:你的高分是 11 秒 但我想要: Nicola:你的高分是 10 秒 托马斯:你的高分是 11 秒

我知道还有一些其他的事情需要修复和改进,但现在,这是我最大的问题。有谁知道该怎么做? (对不起我的名字顺便说一句;)

【问题讨论】:

  • \n 是 Unix 风格的行尾。 Windows 样式为\r\n。几乎所有编辑器都接受这两种格式,但我猜你是在记事本中查看文件:)
  • PrintWriter 的文档应该会有所帮助:println(而不是 append())- 您已经在使用 System.out.println(...) 中的类似 - 所以无需知道这在哪个操作系统上运行既不使用"\n"
  • 这里的exists()/createNewFile()code 完全是浪费时间和空间。 new FileWriter() 已经做到了这一切。你强迫它发生两次。
  • 它是纯 java,看起来与 fx 无关

标签: java string file line-breaks


【解决方案1】:

你需要做的:out.write(System.getProperty("line.separator"));

System.getProperty("line.separator") 将为您提供平台的行分隔符(无论是 Windows/Linux/..)。

【讨论】:

  • System.lineSeparator() 更简单,返回相同
  • 使用println 更简单(因为OP 已经有PrintWriter)
  • 小心使用System.lineSeparator()或System.getProperty("line.separator") windows看不到linux换行符!
  • @CarlosHeuberger 在现场 - 使用可用的最高语义抽象(满足要求)始终是采用的途径
【解决方案2】:

Windows 和 Linux 换行符是不同的。尝试写\r\n。

编辑

如果您使用System.lineSeparator() 获得换行符,它将提供基于平台的换行符。因此,如果您在 unix 上创建一个文件并将其发送给 Windows 用户,他们将看到该文件就像一行一样。但是如果你使用windows os创建文件,linux用户会看到文件是正确的。

【讨论】:

  • OP 应该使用 PrintWriter 提供的更高级别的 api - 这将处理操作系统差异(相对于低级):一般规则是使用可用的最高语义抽象
  • 是的,你写文件是对的,但我的意见是关于读取文件(有操作系统差异)
  • 你用 LineNumberReader 做相反的事情 - 系统规格再次被隐藏:)
猜你喜欢
  • 2011-07-22
  • 2014-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多