有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我用过bw。换行符和“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)
{

}

共 (2) 个答案

  1. # 1 楼答案

    我会使用打印流:

    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
    }
    
  2. # 2 楼答案

    如果您想要遵循相同类型的结构,并使用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 )
    {
    
    }