将多行字符串写入文件

时间:2012-12-08 10:25:01

标签: java bufferedwriter

我使用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");
    }
}

然而,不是一行文字,我希望有一个间隔良好的字符串,这个

<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中有一个就绪函数来构建它吗?

1 个答案:

答案 0 :(得分:3)

如果需要换行,可以使用换行符。

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

\ n将创建一个新行。