簡體   English   中英

如何為文本文件寫一個單獨的行

[英]How to write a separate line for a text file

因此,當我使用FileOutputSstream寫入我的文本文件時,我使用了兩者

fos.write(("0"+"\n").getBytes());

fos.write(System.getProperty("line.separator").getBytes());

它們都不起作用......它們仍然印在同一條線上......

有什么想法嗎?

好的,所以我想出來...出於某種原因,當我在這里嘗試每個例子時,唯一有效的是ps.print(“one \\ r \\ n”); 它真的很奇怪,因為我知道它為什么有效,但確實...

使用PrintStream

例如,System.out是一個PrintStream。

你說你有一個FileOutputStream。 然后,

FileOutputStream f = new FileOutputStream("test.txt");
PrintStream ps = new PrintStream(f);
ps.print("line1");
ps.println(); //this writes your new line
ps.print("line2");
ps.close();

你也可以用;

BufferedWriter fos = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename)));
      fos.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
      fos.newLine();

每個平台的換行符都不同。 對於unix系統(MacOS X,Linux,...和Android,因為它使用修改后的linux內核),行分隔符為0x0A ; 對於MS Windows,它的兩個字節長: 0x0D,0x0A ; 對於老式的MacOS,它是0x0D

這意味着當由一個特別愚蠢的Windows程序(如Notepad.exe)打開時,Android編寫的Android換行符將不可見。 更聰明的程序(例如編程編輯器或IDE)將毫無問題地顯示它。

您可以使用println方法

PrintStream ps=new PrintStream(new FileOutputStream("outputPath"));
for(String line:lines)
    ps.println(line);

用這個:

public  byte[] newLine() {
    byte[] temp = new byte[2];
    temp[0] = 13;
    temp[1] = 10;
    return temp;
}

只需將其寫入FileOuputStream即可。 像這樣:

    FileOutputStream.write(newLine());

這將簡單地寫入字節:13和10。

你必須像這樣附加行分隔符/中斷。

嘗試

String separator = System.getProperty("line.separator");
    fos.append(seperator);

暫無
暫無

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

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