Can we save content from JTextField to a file in Java?


Yes, we can save the content to a file with FileWriter class. Set a JTextFile component as shown below −

JTextField emailId = new JTextField(20);
emailId.setText("abc@example.com");

Set the file location from to where you want to save the content from the JTextField −

String file = "E:\
ew.txt";

Now, with FileWriter, save the content −

FileWriter fileWriter = new FileWriter(file);
emailId.write(fileWriter);
fileWriter.close();

The following is an example to save content from JTextFile to a file. Here, we are saving the text from JTextField to a file at location: “E:\
ew.txt” −

Example

package my;
import java.awt.FlowLayout;
import java.io.FileWriter;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Demo");
      JLabel label;
      frame.setLayout(new FlowLayout());
      label = new JLabel("EmailId : ", SwingConstants.LEFT);
      JTextField emailId = new JTextField(20);
      emailId.setText("abc@example.com");
      String file = "E:\
ew.txt";       FileWriter fileWriter = new FileWriter(file);       emailId.write(fileWriter);       fileWriter.close();       frame.add(label);       frame.add(emailId);       frame.setSize(550,250);       frame.setVisible(true);    } }

Output

Now, the file with the JTextField text will get saved in the specified location i.e −

E:\
ew.txt

The following are the contents of the file now from the JTextField −


Updated on: 30-Jul-2019

908 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements