2014-12-05 42 views
-1

我想保存和加載在我的程序.txt文件。我有讀取和寫入文件的方法,但我希望用戶能夠使用打開/保存表單來選擇文件的名稱和位置。到目前爲止我已經完顯示打開/保存對話框的Java

JButton btnLoad = new JButton("Carregar"); 

btnCarregar.addActionListener(new ActionListener() { 
    private Component modalToComponent; 

    public void actionPerformed(ActionEvent e) { 
     JFileChooser fileChooser = new JFileChooser(); 

     if (fileChooser.showOpenDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) { 
      File file = fileChooser.getSelectedFile(); 
     }   
    } 
}); 

權,這實際上是打開的形式,但在那之後,我不知道在哪裏以及如何使用我的方法來加載文本。我想,我應該使用file,因爲它是選定的文件,但是當我將這個文件發送給我的方法時,它不起作用。任何例子將不勝感激。手前謝謝!

+5

何它不工作?你得到的錯誤是什麼? – Byron 2014-12-05 13:17:02

+1

沒有你展示如何可以使用它錯了,完全與任何及所有的錯誤代碼,很難知道如何給你的意見。 – 2014-12-05 13:19:17

+0

請提供[MCVE(http://stackoverflow.com/help/mcve),我們可以複製粘貼,並出現相同的錯誤,你。你說:「它不起作用」。什麼不工作?保存部分?,打開部分?無論如何,請提供這些代碼。 – Frakcool 2014-12-05 18:13:26

回答

0

您可以從點調用一個方法,其中用戶選擇要打開的文件(在actionPerformed方法的,如果一部分)。所以,如果你的閱讀方法被調用openFile並接受File參數,你可以稱之爲「中openFile(文件)`作爲第二條語句你如果塊:

if (fileChooser.showOpenDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) { 
    File file = fileChooser.getSelectedFile(); 
    openFile(file); 
} 

openFile方法的一個簡單的例子來處理打開文件(在這種情況下,僅印刷的內容)看起來是這樣的:

private void openFile(final File inputFile) { 
    try (final BufferedReader reader = new BufferedReader(new FileReader(inputFile))) { 
     String line; 
     while ((line = reader.readLine()) != null) { 
      System.out.println("line: " + line); 
      // todo: handle line. 
     } 
    } catch (final IOException e) { 
     e.printStackTrace(); 
     // todo: handle exception. 
    } 
} 
+0

謝謝,我沒有使用從選擇的文件,這就是爲什麼它墜毀,有時simpliest的東西是最難的人看到。 – Rogercb 2014-12-05 21:25:03

相關問題