Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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:\new.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:\new.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:\new.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:\new.txt
The following are the contents of the file now from the JTextField −

Advertisements