[英]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.