【问题标题】:How to Press Enter into File in Java [duplicate]如何在Java中按Enter键进入文件[重复]
【发布时间】:2012-10-21 02:26:20
【问题描述】:

可能重复:
Java: How do I get a platform independent new line character?

我想将 enter 写入类 RandomFileAccess 的文件中,但我无法正确执行。

我该怎么办?

喜欢这个代码:

char enter = '\n' ;
outputfile.writeChar(enter);

我正在使用 Windows.... 感谢您的帮助,但它没有工作:(

public class MainClass {
    public static void main(String[] args) {
        String BeforEnter = "It's Before Enter...";
        String Enter = System.getProperty("line.separator");
        String AfterEnter = "It must be on next Line...";

        File MyFile = new File("test.txt");
        try {
            RandomAccessFile TextFile = new RandomAccessFile(MyFile, "rw");
            TextFile.writeChars(BeforEnter);
            TextFile.writeChars(Enter);
            TextFile.writeChars(AfterEnter);
            TextFile.close();

我期待这种文件样式:

在进入之前...

它必须在下一行...

但它会变成这样::(

It's B e f o r e E n t e r 。 . . I t m u s t b e o n n e x t L i n e。 . .

【问题讨论】:

  • “按回车键”是什么意思?你想达到什么目标?如果您只需要换行符,这应该可以正常工作:-/
  • RandomFileAccess?!? DYMRandomAccessFile。以后要多注意复制/粘贴。
  • 另外请注意,如果您的意思是 RandomAccessFile,您不能简单地在任何您喜欢的地方“插入新行”而不冒覆盖以下字符的风险。

标签: java file newline enter


【解决方案1】:

使用System.getProperty("line.separator"); 代替换行符。

根据javadoc

操作系统用来分隔文本文件中的行的序列

【讨论】:

    【解决方案2】:

    您使用的是什么操作系统?最好使用这个:

    String enter = System.getProperty("line.separator");
    

    使用上面的 sn-p,您不必担心换行符的确切细节,因为它们会根据当前使用的操作系统而变化。

    例如,在 Windows 中是 \r\n,在当前的 Mac 和 Linux 中是 \n,在旧版 Mac 中是 \r

    【讨论】:

      猜你喜欢
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 2014-09-20
      • 2021-09-17
      • 2015-06-28
      • 1970-01-01
      相关资源
      最近更新 更多