Search code examples
javabuttonjavafxprintwriterbufferedwriter

How to add new line of text by button?


I have a public method that adds some text from textfield into .txt file, although it works only once. I want that button to add new line of text everytime I click the button (so we can change text in textfield and add it to new line...).

    try {
        ncw = new PrintWriter("database.txt");
        ncw.write(nctext.getText());
        ncw.close();
    } catch (IOException ae) {
        System.out.println("IO Exception");
    }
}

What should I do?


Solution

  • Try this, the second boolean parameter tells FileWriter if it will append or overwrite

    true = append mode

    false= overwrite mode

    FileWriter fw = null;
    BufferedWriter bw = null;
    PrintWriter out = null;
    try{
    
            fw = new FileWriter("database.txt", true);
            bw = new BufferedWriter(fw);
            out = new PrintWriter(bw);
    
                        out.println(nctext.getText());
                        out.flush();
                        out.close();
    
    
       } catch (IOException e) {
                       e.printstacktrace();}