java Java选择文件位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4858497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:21:55  来源:igfitidea点击:

Java select a file location

java

提问by James

I'm not sure if this is even possible as I can't find anything about it after quite a few Google searches.

我不确定这是否可能,因为经过多次 Google 搜索后我找不到任何相关信息。

What I would like to do is on event open up a file dialog box and allow the user to select a folder and then store that folders full directory in a string. So if a user selected a folder in C:\Windows\Example the directory would be stored in String fileDir = C:\Windows\Example;

我想要做的是在事件打开一个文件对话框并允许用户选择一个文件夹,然后将该文件夹的完整目录存储在一个字符串中。因此,如果用户选择了 C:\Windows\Example 中的文件夹,则该目录将存储在 String fileDir = C:\Windows\Example; 中。

Does this make sense? I hope so as I'm struggeling to find the answer. I do apperciate the help, thanks in advance for looking and more thanks if you help me :)

这有意义吗?我希望如此,因为我正在努力寻找答案。我确实得到了帮助,在此先感谢您的关注,如果您能帮助我,我将更加感谢:)

回答by Joseph Gordon

In swing you'll want a JFileChooser.

在 Swing 中,您需要一个JFileChooser

public String promptForFolder( Component parent )
{
    JFileChooser fc = new JFileChooser();
    fc.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );

    if( fc.showOpenDialog( parent ) == JFileChooser.APPROVE_OPTION )
    {
        return fc.getSelectedFile().getAbsolutePath();
    }

    return null;
}

It can be a little awkward selecting folders from a user's perspective. I've watched a lot of folks struggle with it. If you have the time you may want to try my DirectoryChooser. Sorry the code is so crufty; I wrote it awhile back.

从用户的角度选择文件夹可能有点尴尬。我看过很多人为此而挣扎。如果你有时间,你可能想试试我的DirectoryChooser。抱歉,代码太粗糙了;前段时间写的。

回答by miku

You are looking for a FileChooser.

您正在寻找FileChooser

File choosers provide a GUI for navigating the file system, and then either choosing a file or directory from a list, or entering the name of a file or directory. To display a file chooser, you usually use the JFileChooser API to show a modal dialog containing the file chooser.

文件选择器提供用于导航文件系统的 GUI,然后从列表中选择文件或目录,或输入文件或目录的名称。要显示文件选择器,您通常使用 JFileChooser API 来显示包含文件选择器的模式对话框。