如何在Java中将新行字符写入文件
我有一个包含新行的字符串。 我将此字符串发送到函数以将String写入文本文件:
public static void writeResult(String writeFileName, String text) { try { FileWriter fileWriter = new FileWriter(writeFileName); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(text); // Always close files. bufferedWriter.close(); } catch(IOException ex) { System.out.println("Error writing to file '"+ writeFileName + "'");} } //end writeResult function
但是当我打开文件时,我发现没有任何新行。 当我在控制台屏幕中显示文本时,它会以新行显示。 如何在文本文件中编写新行字符。
编辑:假设这是我发送到上述函数的参数text
:
I returned from the city about three o'clock on that may afternoon pretty well disgusted with life. I had been three months in the old country, and was
如何在文本文件中按原样(使用新行)编写此字符串。 我的函数将字符串写在一行中。 你能为我提供一种方法来将文本写入文件,包括新行吗?
编辑2:文本最初是在.txt文件中。 我用以下文字阅读了文字:
while((line = bufferedReader.readLine()) != null) { sb.append(line); //append the lines to the string sb.append('\n'); //append new line } //end while
其中sb
是StringBuffer
在编辑2中:
while((line = bufferedReader.readLine()) != null) { sb.append(line); //append the lines to the string sb.append('\n'); //append new line } //end while
您正在阅读文本文件,并为其添加换行符。 不要追加换行符,换行符不会在一些简单的Windows编辑器(如记事本)中显示换行符。 而是使用以下方法附加特定于操作系统的行分隔符字符
sb.append(System.lineSeparator());
( 对于Java 1.7和1.8 ) 或 sb.append(System.getProperty("line.separator"));
( Java 1.6及以下 )
或者,稍后您可以使用String.replaceAll()
将StringBuffer中构建的字符串中的"\n"
替换为特定于操作系统的换行符:
String updatedText = text.replaceAll("\n", System.lineSeparator())
但是在构建字符串时附加它会更有效,而不是追加'\n'
并在以后替换它。
最后,作为开发人员,如果您使用记事本查看或编辑文件,则应该删除它,因为有更多function强大的工具,如Notepad ++或您喜欢的Java IDE。
BufferedWriter类提供newLine()
方法。 使用它将确保平台独立性。
简单的解决方案
File file = new File("F:/ABC.TXT"); FileWriter fileWriter = new FileWriter(file,true); filewriter.write("\r\n");
bufferedWriter.write(text + "\n");
此方法可以工作,但新行字符在平台之间可能不同,因此您可以使用此方法:
bufferedWriter.write(text); bufferedWriter.newline();
将字符串拆分为字符串数组并使用上面的方法写入(我假设您的文本包含\ n以获取新行)
String[] test = test.split("\n");
而里面是一个循环
bufferedWriter.write(test[i]); bufferedWriter.newline();
将此代码放在您想要插入新行的位置:
bufferedWriter.newLine();
这种方法总是适用于我:
String newLine = System.getProperty("line.separator"); String textInNewLine = "this is my first line " + newLine + "this is my second line ";
这是一个获取当前平台的默认换行符的代码段。 使用System.getProperty("os.name")
和System.getProperty("os.version").
例:
public static String getSystemNewline(){ String eol = null; String os = System.getProperty("os.name").toLowerCase(); if(os.contains("mac"){ int v = Integer.parseInt(System.getProperty("os.version")); eol = (v <= 9 ? "\r" : "\n"); } if(os.contains("nix")) eol = "\n"; if(os.contains("win")) eol = "\r\n"; return eol; }
其中eol是换行符