2012-12-08 60 views
0

我使用的BufferedWriter寫這樣編寫多行字符串到一個文件中

import java.io.BufferedWriter; 
import java.io.FileNotFoundException; 
import java.io.FileWriter; 
import java.io.IOException; 

/** 
* 
* @author Jesus With Issues 
*/ 
public class thewrite { 

    /** 
    * Prints some data to a file using a BufferedWriter 
    */ 
    public void writeToFile(String filename) { 

     BufferedWriter bufferedWriter = null; 

     try { 

      //Construct the BufferedWriter object 
      bufferedWriter = new BufferedWriter(new FileWriter(filename)); 

      //Start writing to the output stream 
      bufferedWriter.write("First Line to be written"); 
      bufferedWriter.newLine(); 
      bufferedWriter.write("Second Line to be written"); 

     } catch (FileNotFoundException ex) { 
      ex.printStackTrace(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } finally { 
      //Close the BufferedWriter 
      try { 
       if (bufferedWriter != null) { 
        bufferedWriter.flush(); 
        bufferedWriter.close(); 
       } 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
     } 
    } 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     new thewrite().writeToFile("filed.txt"); 
    } 
} 

然而,而不是一行文本文件,我想有一個很好liek這

間隔串
<article class="hello"> 
<section> 
<header> 
<h1>Markdown notes</h1> 
<p>Lorem ipsum</p> 
</header> 
<footer> 
<h4>Citations</h4> 
<p>Loremed ipsumed</p> 
</footer> 
</section> 
</article> 

我想寫上面的字符串,一旦寫入完成,我想要一個新的行。是否有一個準備好的函數在bufferedWritter內置來做到這一點?

回答

3

當您需要換行時,可以使用換行符序列。

write("This is a line\nAnd this is a second line"); 

\ n將創建一個新行。

+0

工作得非常好。謝謝。 – Gandalf

相關問題