簡體   English   中英

Java文件OutputStream

[英]Java fileOutputStream

我一直在環顧四周,但找不到我需要的東西。 我正在編寫一個簡單的代碼,將一些字符串保存到.txt文件中。

我在用:

File archivo = new File(FileName);
fileOutputStream.write(toString().getBytes());
fileOutputStream.flush();

當我這樣做時,.txt已成功創建並保存了我需要保存的信息,但是它將所有內容保存在一行中。 如何保存在不同的行中?

打開txt時的示例:

This is line 1This is line 2This is line 3This is line 4

我在每個字符串的末尾添加了“ \\ n”,但它不起作用。

toString()返回一個字符串:“這是第1行”; 作業系統:Windows 7

您可以嘗試執行以下操作:

public void write(final File file, final List<String> lines) throws IOException{
    final BufferedWriter writer = new BufferedWriter(new FileWriter(file)); //new FileWriter(file, true) if you want to append the file (default is false)
    for(final String line : lines){
        writer.write(line);
        writer.newLine();
    }
    writer.flush();
    writer.close();
}

如果您使用的是Java 8,請隨時嘗試使用lambda:

public void write(final File file, final List<String> lines) throws IOException{
    final BufferedWriter writer = new BufferedWriter(new FileWriter(file)); //new FileWriter(file, true) if you want to append the file (default is false)
    lines.forEach(
            l -> {
                try{
                    writer.write(l);
                    writer.newLine();
                }catch(IOException ex){
                    ex.printStackTrace();
                }
            }
    );
    writer.flush();
    writer.close();
}

對於用法,您可以嘗試以下操作:

write(new File(fileName), Arrays.asList("This is line 1", "This is line 2", "This is line 3", "This is line 4"));

使用System.getProperty(“ line.separator”) ,它將返回操作系統用於分隔文本文件中各行的順序。

嘗試這樣。

File archivo = new File(FileName);
fileOutputStream.write(toString().getBytes());
fileOutputStream.write(System.getProperty("line.separator").getBytes());
fileOutputStream.flush();

參考: http : //docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

暫無
暫無

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

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