2013-10-15 48 views
1

Iam是java初學者。 我寫了一個簡單的程序,使用JFileChooser中的showSaveDialoge()將一些內容寫入文件。代碼包括下面。未在Java中使用JFileChooser保存文件

public static void main(String arg[]) throws IOException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException 
    { 
     JFrame frame = new JFrame(); 
     JFileChooser fc = new JFileChooser(); 
     try { 
      File file = new File("fileName.txt"); 
      fc.setSelectedFile(file); 
      int r = fc.showSaveDialog(frame); 
      if(r == JFileChooser.APPROVE_OPTION) 
      { 
       FileWriter writer = new FileWriter(file); 
       writer.append("Data inside the file"); 
       writer.flush(); 
       writer.close(); 
      } 
      else if(r == JFileChooser.CANCEL_OPTION) { 
       System.out.println("Do nothing for CANCEL"); 
      } 
     } catch (Exception ex) { 
      JOptionPane.showMessageDialog(null, "File could not be written, try again."); 
     } 
    } 

該代碼被執行並且保存對話框已經到來。但是當我點擊「對話框」上的「保存」按鈕時,什麼都沒有發生。該文件沒有保存在選定的位置。可能是什麼原因? 在此先感謝。

回答

6

什麼是hapenning是:

創建在您的當前位置與名稱的文件FILENAME.TXT

File file = new File("fileName.txt"); //could be $HOME$/fileName.txt 

用戶選擇PROGRAMFILES/file.txt的

,但你使用的FileWritter文件信息,而不是來自FileChooser的用戶。

變化

FileWriter writer = new FileWriter(file); 

FileWriter writer = new FileWriter(chooser.getSelectedFile()); 
+0

非常感謝RamonBoza。它的工作。然後標記爲: – Sajeev

+0

標記爲:P – RamonBoza

1

試試這個:

  FileWriter writer = new FileWriter(fc.getSelectedFile()); 

應該從文件選擇器寫入選定的文件。

您正在寫入fileName.txt中,該文件將被保存在您運行程序的當前目錄中。