如何在java swing库中浏览文件?

Tom*_*mek 34 java swing file

我想知道在java swing库中是否有某种J工具打开文件浏览器窗口并允许用户选择文件.然后文件的输出将是所选文件的绝对路径.

提前致谢,

CMS*_*CMS 38

您可以使用JFileChooser类,查看此示例.

  • 如果您不需要JFileChooser的所有灵活性,则应该使用java.awt.FileDialog.您的OS X用户会感谢您.FileDialog使用本机文件选择器窗口,而JFileChooser是一个swing组件,缺少键盘快捷键和其他细节. (27认同)

Tom*_*mek 15

我最终使用了这段快速完成我需要的代码:

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

try {
    // Open an input stream
    Scanner reader = new Scanner(fc.getSelectedFile());
}
Run Code Online (Sandbox Code Playgroud)


ibe*_*rck 7

以下示例创建一个文件选择器,并将其显示为第一个打开文件对话框,然后显示为保存文件对话框:

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();
Run Code Online (Sandbox Code Playgroud)

这是一个更精细的示例,它创建了两个用于创建和显示文件选择器对话框的按钮.

// 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();
    }
};
Run Code Online (Sandbox Code Playgroud)