#5, First Floor, 4th Street , Dr. Subbarayan Nagar, Kodambakkam, Chennai-600 024 pro@slogix.in

Office Address

  • #5, First Floor, 4th Street Dr. Subbarayan Nagar Kodambakkam, Chennai-600 024 Landmark : Samiyar Madam
  • pro@slogix.in
  • +91- 81240 01111

Social List

How to write data into file in java?

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.

Sample Code
  • Filename: WriteIntoFile .java

import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class WriteIntoFile {
JPanel panel;
JFrame jf;
JLabel label1,label2;
JButton Write;
JTextField textfield1,textfield2,textfield3;
JPasswordField passwordfield;
JTextArea textArea1;
public WriteIntoFile() {
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);
Write=new javax.swing.JButton("Write");
Write.setFont(new Font("Monotype Corsiva", Font.BOLD, 24));
Write.setBounds(270,350,140,30);
jf.add(Write);
}
public void handlingEvents() {
Write.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
String filename = textfield1.getText();
String content = textArea1.getText();
FileWriter fw = new FileWriter(filename);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
fw.close();

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

}


Screenshots