java里如何点击button后将textfield的输入内容存入创建的txt文件里?

2025-04-13 18:24:27
推荐回答(4个)
回答1:

首先对save按钮增加一个监听事件,然后在监听事件里面进行textfield取值,代码如下:

JButton savebtn = new JButton("save");
savebtn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String val= textfield.getText();
        ....增加其他的文本框取值
    }
});

回答2:

直接用getText()获取输入内容,然后用I/O流的形式保存到txt中呀。感觉你的界面好高端的样子,用哪个软件实现的呢

回答3:

将下面的代码放在main函数里面执行一下,将大写转成小写,前提是这个文件存在D:/lin/testfile.txt
public static void ToLowerCase() throws IOException{
File file = new File("D:/lin/testfile.txt");
InputStreamReader in = new InputStreamReader(new FileInputStream(file),"gbk");
BufferedReader bufferedReader = new BufferedReader(in);
String lineTxt = null;
String test = "";
while((lineTxt = bufferedReader.readLine()) != null){
test = lineTxt.toLowerCase();
System.out.println(test);
}
FileWriter fw = new FileWriter(file);
fw.write("");
fw.close();
in.close();
OutputStream out = new FileOutputStream(file,true);
out.write(test.getBytes("GBK"));
out.close();
}
//将在控制台中输入的字符保存在txt文件中
public static void save() throws IOException{
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
(new File("D:/lin/testfile.txt")).delete();
//在d盘上创建一个名为testfile的文本文件
File f = new File("D:/lin"+File.separator+"testfile.txt");
//用FileOutputSteam包装文件,并设置文件可追加
OutputStream out = new FileOutputStream(f,true);
out.write(input.getBytes("GBK"));
out.close();
}

回答4:

添加JButton的ActionPerfoirm,里面调用JTextFiled.getText(),结果存入字符串,用File类和outputStream类写入文件。