gpt4 book ai didi

java - 扫描 jtextfield 进行输入,写入文本文件,再次扫描新输入,直到用户关闭面板

转载 作者:行者123 更新时间:2023-12-01 14:12:00 24 4
gpt4 key购买 nike

我是一个新手,我这里有一个程序,它扫描两个 jtextfields 中的输入并将输入写入两个文本文件。我尝试为两个 jtextfields 输入新的输入,但显然它不会将新的输入写入文本文件。这是我的代码。有人可以帮我吗?

        File outFile = new File("Z://Question.txt");
FileOutputStream outFileStream = new FileOutputStream(outFile);
PrintWriter outStream = new PrintWriter(outFileStream);
File outFile2 = new File("Z://Answer.txt");
FileOutputStream outFileStream2 = new FileOutputStream(outFile2);
PrintWriter outStream2 = new PrintWriter(outFileStream2);

JTextField question = new JTextField(30);
JTextField answer = new JTextField(15);

File inFile = new File("Z://Question.txt");
FileReader myFileReader = new FileReader(inFile);
Scanner sc = new Scanner(myFileReader);
File inFile2 = new File("Z://Answer.txt");
FileReader myFileReader2 = new FileReader(inFile2);
Scanner sc2 = new Scanner(myFileReader2);

rate.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
String ques = question.getText();
String ans = answer.getText();
outStream.write(ques);
outStream.close();
outStream2.write(ans);
outStream2.close();
String s = sc.nextLine();
String[] question2 = s.split(" ");
System.out.print("Question: ");
for (int i = 0; i < question2.length; i++) {
System.out.print(question2[i] + " ");
x++;
} //debug
String[] QEquivalent = new String[question2.length];
System.out.println();
System.out.println("Number of words in the question: " + x);
String s2 = sc2.nextLine();
String[] Answer = s2.split(" ");
System.out.print("Answer/s: ");
for (int c = 0; c < Answer.length; c++) {
System.out.print(Answer[c] + " ");
}
}
});

最佳答案

当您仅通过传入文件来构造 FileOutputStream 时,默认情况下,它不会追加。为了确保它附加,您需要做的是 new FileOutputStream(file, true);

此外,我还没有测试您的代码,但看来您正在关闭流,而仅声明和初始化流一次,因此下次您尝试编写时,它将失败,因为流已关闭。尝试将 close() 替换为 flush(),并向您的 JFrame 添加一个 WindowListener。然后,您可以在 windowClosing 上关闭流。据我所知,您需要对流进行全局声明。

关于java - 扫描 jtextfield 进行输入,写入文本文件,再次扫描新输入,直到用户关闭面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18447910/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com