2013-01-23 119 views
0

使用以下代碼我可以將program.txt存儲在工作項目文件夾中,但是如何使用JFileChooser或任何其他選項將文件保存在選定位置?如何使用JFileChooser在所需位置保存.txt文件

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(); 
      } 
     } 
    }); 
+0

[如何保存的文件可能重複做這樣使用JFileChooser?](http://stackoverflow.com/questions/2531037/how-to-save-file-using-jfilechooser) –

回答

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 
} 
+0

我希望用戶創建一個文件,然後寫上。 –

+0

@ user2003602我已經更改爲'showSaveDialog',然後'FileWriter'會創建文件。 –

+0

仍然沒有工作:-(,我可以編譯它沒有錯誤,但它不會創建任何文件 –