繁体   English   中英

将多行字符串写入文件

[英]Writing a multi line string to a file

我正在使用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中是否有准备好执行此操作的函数?

想要换行时,可以使用换行序列。

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

\\ n将创建一个新行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM