尝试将数据发送到文本文件

时间:2015-08-08 15:23:06

标签: java jbutton jtextfield

大家好,我制作了一个由jtextfield和几个jbuttons组成的程序。我想按下一个jbutton,以便将jtextfields保存到计算机中。任何帮助都会有用。

1 个答案:

答案 0 :(得分:0)

我认为这会对你有帮助..

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    if (jTxt_text.getText().isEmpty()) {
        JOptionPane.showMessageDialog(rootPane, "Field is empty. Fill the filed and try again.");
    } else {
        //get the text from the jTextField and save it into a varibale. 
        String inputText = jTxt_text.getText();
        //Where to save the file.
        String savePath = "C:/test/sample.txt";

        //Creating a file object, file is an abstract representation of file and directory pathnames.
        File tempFile = new File(savePath);

        //Check wther the file is available or not.
        if (!tempFile.exists()) {
            try {
                //Creates the file if it's not exsising.
                tempFile.createNewFile();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        try {
            //writing process..
            FileWriter tempWriter = new FileWriter(tempFile.getAbsoluteFile());
            BufferedWriter tempBufferWriter = new BufferedWriter(tempWriter);
            tempBufferWriter.write(inputText);
            tempBufferWriter.close();

            JOptionPane.showMessageDialog(rootPane, "Text file with the written text is successfully saved.");
            jTxt_text.setText(null);

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}  

这段代码仍存在一个小问题tempBufferWriter.write(inputText)返回void所以..我不知道如何从代码本身检查过程是否成功完成..