簡體   English   中英

使用\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\。

[英]“\n” not adding new line when saving the string to text using BufferWriter to text file

大家好,我試圖在現有文件中添加新的字符串行,但是我將代碼附加到了最后一個字符串上。 我通過在添加到文件的字符串中添加新的換行符來修復它,是否有另一種方法可以在文件末尾的新行中添加字符串,而無需在字符串的開頭添加新的換行符?

String name = "\nbob";
BufferedWriter out = new BufferedWriter(new FileWriter("names.txt",true));
    out.write(name);
    out.close();

當前文件:

bill
joe
john

追加后

bill
joe
john
bob

追加而不換行

bill
joe
johnbob

您可以在將新名稱寫出到文件之前使用newLine()方法。

\\n將被附加到您的文件中; 但顯然您只是以一種認為沒有換行符的方式查看它。

如果您使用的是Windows,則\\n不是正確的行分隔符:請改用\\r\\n

String name = "\r\nbob";

Windows使用\\r\\n作為其行分隔符; 和記事本之類的工具(仍然)無法正確處理非Windows的行尾。

請注意,使用out.newLine()不一定是正確的方法:這意味着將使用當前平台的行分隔符。 可能是正確的。 但是,如果您正在* nix上運行此代碼,並且原始文件是在Windows上生成的(並且必須繼續在Windows上正確讀取),則不會,因為將使用\\n “編寫一次,隨處運行”在這里不太起作用。

它使用Java7。BufferedWritter類提供了newLine()方法來換行。 您可以按照此示例。 示例鏈接

 import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class BufferedWriterDemo { //file path private static final String FILENAME = "/home/farid/Desktop/bw.txt"; public static void main(String[] args) { //BufferedWriter api //https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html try(BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME))) { String str = "This is the content to write into file"; //write method bw.write(str); //break new line bw.newLine(); String seconStr = "This is the content to write into file."; //write method bw.write(seconStr); //break new line bw.newLine(); //console print message System.out.println("Successfully compeleted"); //BufferedWritter close bw.flush(); bw.close(); } catch (IOException e) { e.printStackTrace(); } } } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM