java中如何选择文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40255039/
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-08-11 22:33:11  来源:igfitidea点击:

How to choose file in java?

javafilepath

提问by Hemanth S. Vaddi

I need to get file path for my java program during runtime. Is there any way to use default dialog boxto choose a single fileand get its full path and name?

我需要在运行时获取我的 java 程序的文件路径。有没有办法使用默认对话框来选择单个文件并获取其完整路径和名称?

Its just picking a file and get its path into a String object

它只是选择一个文件并将其路径放入一个 String 对象中

Can you please provide the code for it or a tutorial?

你能提供它的代码或教程吗?

PS: Windows OS

PS:Windows 操作系统

采纳答案by matt

Here is the example from the JFileChooserdocs copy pasta with the parent sent to null.

这是JFileChooser文档复制面食中的示例,父级发送到null.

public class PickAFile {
    public static void main(String[] args){
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
                "JPG & GIF Images", "jpg", "gif");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showOpenDialog(null);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            System.out.println("You chose to open this file: " +
                    chooser.getSelectedFile().getName());
        }
    }
}

If you don't like the look of the JFileChooser try the FileDialog.

如果您不喜欢 JFileChooser 的外观,请尝试使用FileDialog.

    FileDialog dialog = new FileDialog((Frame)null, "Select File to Open");
    dialog.setMode(FileDialog.LOAD);
    dialog.setVisible(true);
    String file = dialog.getFile();
    System.out.println(file + " chosen.");