繁体   English   中英

使用Java写入Mac和Windows的文件

[英]Writing to file for mac and windows with java

在Windows中写入文件时出现问题。 我的JAVA程序在Mac上可以正常运行,但是在Windows中却无法运行。

这是在Windows中执行不同的代码:

String string = textArea.getText();

if (string.contains(System.getProperty("line.separator"))) {
    notatet = string.replace(System.getProperty("line.separator"), "<line.separator>");
}

当我将此字符串保存到MAC中的txt文件中时,得到以下信息:

Line1<line.separator>Line2<line.separator><line.separator>Line3

但是当我将此字符串保存到WINDOWS中的txt文件时,我得到了:

Line1
Line2

Line3

现在我显然想要Mac选件,这是我的目标。 我应该如何处理我的代码才能使其在两个/所有操作系统中都能工作?

问题在于您的字符串中可能有\\r\\n或有\\n作为行分隔符。 这与您的if语句不匹配。 只需使用正则表达式和replaceAll方法即可。

请参见以下示例:

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String string = "Test\ntest\r\ntest";
        String n = string.replaceAll("[\\r\\n]+", "<line.separator>");
        System.out.print(n);
    }
}

输出:Testtesttest

运行示例

编辑

对于Test\\n\\ntest\\r\\ntest这种情况,上面的代码无法正常工作。 将正则表达式替换为以下几行:

    String n = string.replaceAll("\\n", "<line.separator>");
    n = n.replaceAll("\\r", "");

因此,如果出现一个以上的\\r\\n\\n替换项将正常工作。 因为所有情况都包含\\n所以首先将这些行替换为<line.separator> ,然后再行n.replaceAll("\\\\r", ""); 进行清理并删除不必要的\\r

有一个易于使用的Linebreak matcher \\R ,它应该处理所有各种\\n\\r\\r\\n组合。

String text = "A\r\nB\n\nC\rD\rE\r\rF";
String res = text.replaceAll("\\R", "<line.separator>");
System.out.println(res);

将打印

A<line.separator>B<line.separator><line.separator>C<line.separator>D<line.separator>E<line.separator><line.separator>F

并且应该在每个OS上都可以使用。

编辑\\R是Java 8的新功能。对于较早版本,可以使用\ \ |[\ \ \ \ \…\
\
]

String res = text.replaceAll("\\u000D\\u000A|[\\u000A\\u000B\\u000C\\u000D\\u0085\\u2028\\u2029]",
    "<line.separator>");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM