如何使用JFileChooser将.txt文件保存在所需位置

时间:2013-01-23 12:40:27

标签: java swing file-io jfilechooser java-io

使用以下代码我可以将program.txt存储在工作项目文件夹中,但是如何使用JFileChooser或任何其他选项将文件保存在选定位置?

b2.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            try {

                o = new BufferedWriter(new FileWriter("program.txt"));

                o.write(t1.getText());
                o.write(",");
                o.write(t2.getText());
                o.write(",");
                o.write(t3.getText());
                o.write(",");
                o.write(t4.getText());
                o.write(",");
                o.write(t5.getText());
                o.write(",");
                o.write(t6.getText());
                o.write(",");
                o.write(t7.getText());
                o.write(",");
                o.close();


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

2 个答案:

答案 0 :(得分:3)

final JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(aComponent); //parent component to JFileChooser
if (returnVal == JFileChooser.APPROVE_OPTION) { //OK button pressed by user
        File file = fc.getSelectedFile(); //get File selected by user
        o = new BufferedWriter(new FileWriter(file)); //use its name

        ...
        //your writing code goes here
}

答案 1 :(得分:0)

您可以通过在JFileChooser对象

中设置File对象来执行此操作
File f = new File("filename");
myJFileChooser.setSelectedFile(f);

查看此帖子了解更多

http://www.coderanch.com/t/561950/GUI/java/Save-JTextArea-JFileChooser-TXT-file