我正在使用GUI进行用户输入。我的主要目标是记录用户将输入的任何内容并将其发送到文件"file.txt"。
但是每当我打开文件时,它都是空的,即使我已经在文本字段中输入了内容。它仍然返回空。我是Java的初学者。
package testpath;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class Testpath extends JFrame {
JLabel label;
JTextField tf;
JButton button;
public Testpath(){
setLayout(new FlowLayout());
label= new JLabel("Enter First Name");
add(label);
tf=new JTextField(10);
add(tf);
button=new JButton("Log In");
add(button);
event e=new event();
button.addActionListener(e);
}
public class event implements ActionListener{
public void actionPerformed(ActionEvent e){
try{
String word=tf.getText();
FileWriter stream= new FileWriter("C://Users//Keyboard//Desktop//file.txt");
BufferedWriter out=new BufferedWriter(stream);
out.write(word);
}catch (Exception ex){}
}
}
public static void main(String[] args) {
Testpath gui=new Testpath();
gui.setLocationRelativeTo(null);
gui.setVisible(true);
gui.setSize(400,250);
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
您永远不会关闭流,因此其内容永远不会写入磁盘。
只需在out.write();
后致电out.close();
即可。
如果您希望将内容写入磁盘而不同时关闭流,则可以使用 out.flush();
。(谢谢@Ultraviolet)