【问题标题】:Writing a multi line string to a file将多行字符串写入文件
【发布时间】:2012-12-08 10:25:00
【问题描述】:

我正在使用 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中是否有一个准备好的函数来做这个?

【问题讨论】:

    标签: java bufferedwriter


    【解决方案1】:

    当你想要换行时,你使用换行序列。

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

    \n 将创建一个新行。

    【讨论】:

      猜你喜欢
      • 2013-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 2019-09-04
      相关资源
      最近更新 更多