我是新手,我在这里有一个程序扫描两个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] + " ");
}
}
});
答案 0 :(得分:1)
通过仅传入文件构造FileOutputStream
时,默认情况下,它不会附加。您需要做的是确保其附加是new FileOutputStream(file, true);
另外,我还没有测试过您的代码,但是看起来您正在关闭流,而只是声明和初始化您的流只有一次,所以下次尝试写入时会因为流关闭而失败。尝试使用close()
替换flush()
,并在WindowListener
添加JFrame
。然后,您可以在windowClosing
关闭您的信息流。据我所知,你需要制作你的流全局声明。