0

我是一个新手,我在这里有一个程序可以扫描两个 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] + " ");
        } 
        }
        });
4

1 回答 1

1

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

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

于 2013-08-26T15:56:00.560 回答