Append text into Existing File

Description

Data into the file is written using the FileWriter Object available in java.io package that writes the data as string. File name and content to be written in the file can be given as input in GUI. FileWriter constructor with boolean argument (true) is called for creating FileWriter Object to append the data into the existing file.

  • Filename:AppendIntoFile .java

import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class AppendIntoFile {

JPanel panel;
JFrame jf;
JLabel label1,label2;
JButton Append;
JTextField textfield1,textfield2,textfield3;
JPasswordField passwordfield;
JTextArea textArea1;
public AppendIntoFile() {
initComponents();
handlingEvents();
}

public void initComponents() {
jf=new javax.swing.JFrame();
jf.setTitle("Data From File");
jf.setLayout(null);
jf.setSize(800,500);
jf.show();
jf.setVisible(true);

JScrollPane scrollBar=new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jf.add(scrollBar);
label1=new javax.swing.JLabel("Filename");
label1.setFont(new Font("Monotype Corsiva", Font.BOLD, 24));
label1.setBounds(50,80,200,40);
jf.add(label1);
textfield1=new javax.swing.JTextField();
textfield1.setFont(new Font("Monotype Corsiva", Font.BOLD, 18));
textfield1.setBounds(250,80,200,30);
jf.add(textfield1);
textArea1=new javax.swing.JTextArea();
textArea1.setFont(new Font("Monotype Corsiva", Font.BOLD, 18));
textArea1.setLineWrap(true);
textArea1.setWrapStyleWord(true);
JScrollPane scrollBar1=new JScrollPane(textArea1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollBar1.setBounds(250,120,200,200);
jf.add(scrollBar1);
Append=new javax.swing.JButton("Append");
Append.setFont(new Font("Monotype Corsiva", Font.BOLD, 24));
Append.setBounds(270,350,140,30);
jf.add(Append);
}
public void handlingEvents() {
Append.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
String filename = textfield1.getText();
String content = textArea1.getText();
FileWriter fw = new FileWriter(filename,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
fw.close();
JOptionPane.showMessageDialog(null,"Text is append into the file "+filename);

}
catch(Exception e) {
System.out.println(e);
}
}
});
}
public static void main(String args[]) {
AppendIntoFile ap = new AppendIntoFile();
}
}