-1

I have this line:

//Creating an image
Image image = new Image(new FileInputStream("C:\\images\\image.png"));

I would like to change to this line, I would like to get the image from resources in IntelliJ and not from my PC's C drive, for example, but it doesn't work:

Image image = new Image(new FileInputStream("file:src/main/resources/images/image.png"));

or

Image image  = new Image(getClass().getResource("file:src/main/resources/images/image.png").toExternalForm());

I have an exception:

Caused by: java.lang.RuntimeException: Exception in Application start method

Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
  • what is the full stack trace for the exception? And why not just use `Image image = new Image(getClass().getResource("image.png").toExternalForm());` provided image.png is in the same package hierarchy in resources as the calling class ` – b3tuning Jun 08 '20 at 08:03
  • ie: the calling class is in `src/main/java/some/package` then image.png will be in `src/main/resources/some/package` – b3tuning Jun 08 '20 at 08:09
  • It doesn't work. I put image.png to the the same package what class file. I have tried put image.png to the resources but it doesn't work as well. – SJaySimpson Jun 08 '20 at 08:10
  • Please show the relative path of the class calling for new image, the relative path of where you have image.png, and the full exception stacktrace – b3tuning Jun 08 '20 at 08:13
  • I posted everything in my post. What does it mean the full exception stacktrace? – SJaySimpson Jun 08 '20 at 08:19
  • 2
    Try ```Image image = new Image(getClass().getClassLoader().getResourceAsStream("images/image.png"));``` – Felix Jun 08 '20 at 08:24
  • `Caused by: java.lang.RuntimeException: Exception in Application start method` does not give enough information for anyone to help you.. The class calling for a new Image (I'm guessing Application.java) is the path `src/main/java/Application.java`? if it is, then to use my suggested code, image.png file must have the path `src/main/resources/image.png'. You did not use my suggestion, but instead modified it, there is no reason to put `file:` and you didn't move the image.png to where it needs to be for the class loader to pick it up via the call to getResource – b3tuning Jun 08 '20 at 08:25
  • @codeflush.dev has the correct answer if you don't want to move the file – b3tuning Jun 08 '20 at 08:26
  • @codeflush.dev yes, it works – SJaySimpson Jun 08 '20 at 08:41

2 Answers2

0

You simply need do like this.

In project put your images:

ProjectName/image.png

example of the project

and then

   Image image = new Image(new FileInputStream("image.png"));
William
  • 16
  • 6
0

The path is determined from the classpath (= root) which is the case of src/main/resources. Thus

Image image  = new Image(getClass().getClassLoader().getResourceAsStream("/images/image.png")); 

...should work.

You get get some more details here.

C.Champagne
  • 5,381
  • 2
  • 23
  • 35