【问题标题】:Portable newline transformation in JavaJava中的便携式换行符转换
【发布时间】:2013-08-25 12:05:19
【问题描述】:

假设我有一个字符串,它由几行组成:

aaa\nbbb\nccc\n(在 Linux 中)或 aaa\r\nbbb\r\nccc(在 Windows 中)

我需要在字符串的每一行中添加字符#,如下所示:

#aaa\n#bbb\n#ccc(在 Linux 中)或 #aaa\r\n#bbb\r\n#ccc(在 Windows 中)

什么是最简单且可移植(在 Linux 和 Windows 之间)的 Java 方式?

【问题讨论】:

    标签: java string newline


    【解决方案1】:

    使用line.separator 系统属性

    String separator = System.getProperty("line.separator") + "#"; // concatenate the character you want
    String myPortableString = "#aaa" + separator + "ccc";
    

    这些属性有更详细的描述here

    如果您打开PrintWriter 的源代码,您会注意到以下构造函数:

    public PrintWriter(Writer out,
                       boolean autoFlush) {
        super(out);
        this.out = out;
        this.autoFlush = autoFlush;
        lineSeparator = java.security.AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction("line.separator"));
    }
    

    它正在获取(并使用)系统特定的分隔符以写入OutputStream

    您始终可以在属性级别进行设置

    System.out.println("ahaha: " + System.getProperty("line.separator"));
    System.setProperty("line.separator", System.getProperty("line.separator") + "#"); // change it
    System.out.println("ahahahah:" + System.getProperty("line.separator"));
    

    打印

    ahaha: 
    
    ahahahah:
    #
    

    所有请求该属性的类现在都将获得{line.separator}#

    【讨论】:

      【解决方案2】:

      我不知道你到底在用什么,但是PrintWriterprintf 方法可以让你编写格式化的字符串。使用字符串,您可以使用%n 格式说明符,它将输出特定于平台的行分隔符。

      System.out.printf("first line%nsecond line");
      

      输出:

      first line
      second line
      

      System.outPrintStream,它也支持这个)。

      【讨论】:

        【解决方案3】:

        从 Java 7 开始(也注明 here),您还可以使用该方法:

        System.lineSeparator()
        

        等同于:

        System.getProperty("line.separator")
        

        获取系统相关的行分隔符字符串。 下面引用来自官方JavaDocs的方法描述:

        返回系统相关的行分隔符字符串。它总是返回 相同的值 - 系统属性的初始值 行分隔符。

        在 UNIX 系统上,它返回“\n”;在 Microsoft Windows 系统上 返回“\r\n”。

        【讨论】:

          猜你喜欢
          • 2012-06-27
          • 2012-01-31
          • 2014-02-17
          • 1970-01-01
          • 2014-09-12
          • 2011-07-04
          • 2023-03-22
          • 1970-01-01
          • 2016-07-14
          相关资源
          最近更新 更多