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

时间:2008-11-12 01:58:25

标签: java swing file

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

提前致谢,

4 个答案:

答案 0 :(得分:38)

您可以使用JFileChooser课程,查看this example

答案 1 :(得分:14)

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

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

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

答案 2 :(得分: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();

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

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

答案 3 :(得分:0)

在WebStart和新的6u10 PlugIn中,即使没有安全权限,也可以使用FileOpenService。出于显而易见的原因,您只获取文件内容,而不是文件路径。