如何在java中的现有文本文件中添加新行?

时间:2016-03-24 23:04:52

标签: java

我使用过bw.newline和" n / n"但是当有新的输入时,似乎没有任何东西将它们分开。

try
{       
    FileWriter filewriter = new FileWriter("transactions",true);
    BufferedWriter bw = new BufferedWriter(filewriter);
    bw.newLine();
    bw.write("Withdrawn"+ " "+withdraw+ "\r\n"+ "Balance" + " "+initialamount.get(Wd)+"\r\n"+
            " "+ date);

    bw.close();

}
catch ( IOException e)
{

}

3 个答案:

答案 0 :(得分:0)

我会使用PrintStream:

try(PrintStream printStream = new PrintStream("transactions"))
{       
    printStream.println();
    printStream.println("Withdrawn " + withdraw);
    printStream.println("Balance " + initialamount.get(Wd));
    printStream.println(date);
}
catch ( IOException e)
{
    //You should do something here
}

答案 1 :(得分:0)

如果您想使用相同类型的结构并使用FileWriterBufferedWriter,那么您需要以下内容:

try
{
    FileWriter filewriter = new FileWriter("src/resources/test.txt",true);
    BufferedWriter bw = new BufferedWriter(filewriter);
    bw.write("Withdrawn: " + withdraw +"\n");
    bw.write("Balance: " +initialamount.get( Wd ) + date );
    bw.newLine();
    bw.close();
}
catch ( IOException ignored )
{

}

答案 2 :(得分:0)

您是否尝试过使用PrintWriter类?

FileWriter filewriter = new FileWriter("src/resources/test.txt",true);
PrintWriter pw = new PrintWriter(filewriter);
pw.println();
pw.println("Withdrawn " + withdraw);
pw.println("Balance " + initialamount.get(Wd));
pw.println(date);

它也应该处理异常