-1

After I've searched for a solution for my problem & reading similar questions which are very more professional than mine,... well, I hope you pay attention to my problem, even though it seems simple! I'm working on a project which open files by FileChooser, then I'm trying to show it on a pane. The problem is getClass().getResourceAsStream(file.getAbsolutePath()) returns null.So while I can print the path & see it's true, but I cannot use it in creating images. Part of my code is:

    FileChooser fileChooser = new FileChooser();
    File file = fileChooser.showOpenDialog(stage);

...

     Image img = new Image(getClass().getResourceAsStream(file.getAbsolutePath());

The exception is:

    Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Input stream must not be null ...

I work on Ubuntu by NetBeans. I really appretiate helps. Thanks.

TEB
  • 7
  • 1
  • 7

1 Answers1

1

Use ImageIO:

Image img = ImageIO.read(file);

getResourceAsStream requires a path on the class path. As the resource could be in a jar, its full URI would be jar:file:/..../xyz.jar!/.... And File is on the file system.

One cannot mix those, only Path is a new generalisation allowing paths in several "file" systems.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Thank you, but I want to use file systems. Actually I want to fix this problem & after that expend the class for every type of files. For now, I want to see if I can do sth like photoshop does. – TEB Dec 11 '19 at 15:47
  • To be clear: the above works with your FileChooser, picking a File on the phyisical disk. And ImageIO can also read from any InputStream, not just File. – Joop Eggen Dec 11 '19 at 16:47
  • Thank you very much. I will read about it more & more to understand better what you've taught me. – TEB Dec 11 '19 at 17:32