如何使用FileChooser中的路径获取图像的绝对路径?

时间:2016-06-21 08:19:52

标签: java file javafx path filechooser

我想要的是当用户选择一个带有文件选择器的图像在屏幕上显示时。

            FileChooser fc = new FileChooser();
            File selectedFile = fc.showOpenDialog(null);

            if(selectedFile != null)
            {
               // Absolute path from file is: G:\Stvari\Daki Matura\IMG_6746.JPG
                Image img = new Image(selectedFile.getAbsolutePath());
                iv.setImage(img);

            }

当我这样做时,我得到异常:java.lang.IllegalArgumentException 来自文件选择器的绝对路径不起作用。但如果我改变它

来自:" G:\ Stvari \ Daki Matura \ IMG_6746.JPG"

to:" file:/// G:// Stvari // Daki Matura // IMG_6746.JPG"然后它完成了工作。

有没有办法解决这个问题,所以我不需要编辑路径?

1 个答案:

答案 0 :(得分:0)

使用File.toURI().toString()

    FileChooser fc = new FileChooser();
    File selectedFile = fc.showOpenDialog(null);

    if (selectedFile != null) {
        Image img = new Image(selectedFile.toURI().toString());
        iv.setImage(img);
    }