2008-11-12 54 views

回答

37

可以使用JFileChooser類,檢查this example

+27

如果您不需要JFileChooser的所有靈活性,則應該改爲使用java.awt.FileDialog。你的OS X用戶會感謝你。 FileDialog使用本機文件選擇器窗口,而JFileChooser是一個swing組件,並且缺少鍵盤快捷鍵和其他細節。 – 2009-04-28 14:34:38

12

我結束了使用這種快速一塊是做正是我需要的代碼:

final JFileChooser fc = new JFileChooser(); 
fc.showOpenDialog(this); 

try { 
    // Open an input stream 
    Scanner reader = new Scanner(fc.getSelectedFile()); 
} 
6

下面的示例創建一個文件選擇器,並將其顯示爲第一個打開的文件對話框,然後作爲save-文件對話框:

String filename = File.separator+"tmp"; 
JFileChooser fc = new JFileChooser(new File(filename)); 

// Show open dialog; this method does not return until the dialog is closed 
fc.showOpenDialog(frame); 
File selFile = fc.getSelectedFile(); 

// Show save dialog; this method does not return until the dialog is closed 
fc.showSaveDialog(frame); 
selFile = fc.getSelectedFile(); 

這是一個更詳細的示例,它創建兩個按鈕來創建和顯示文件選擇器對話框。

// This action creates and shows a modal open-file dialog. 
public class OpenFileAction extends AbstractAction { 
    JFrame frame; 
    JFileChooser chooser; 

    OpenFileAction(JFrame frame, JFileChooser chooser) { 
     super("Open..."); 
     this.chooser = chooser; 
     this.frame = frame; 
    } 

    public void actionPerformed(ActionEvent evt) { 
     // Show dialog; this method does not return until dialog is closed 
     chooser.showOpenDialog(frame); 

     // Get the selected file 
     File file = chooser.getSelectedFile(); 
    } 
}; 

// This action creates and shows a modal save-file dialog. 
public class SaveFileAction extends AbstractAction { 
    JFileChooser chooser; 
    JFrame frame; 

    SaveFileAction(JFrame frame, JFileChooser chooser) { 
     super("Save As..."); 
     this.chooser = chooser; 
     this.frame = frame; 
    } 

    public void actionPerformed(ActionEvent evt) { 
     // Show dialog; this method does not return until dialog is closed 
     chooser.showSaveDialog(frame); 

     // Get the selected file 
     File file = chooser.getSelectedFile(); 
    } 
}; 
0

在WebStart和新的6u10 PlugIn中,即使沒有安全權限,也可以使用FileOpenService。出於顯而易見的原因,您只能獲取文件內容,而不是文件路徑。