Issue
I have MainClass
public class MainClass extends Application {
@Override
public void start(Stage primaryStage) {
try{
Image img = new Image(getClass().getResourceAsStream(".\\build\\resources\\main\\img\\h1.jpg"));
System.out.println("ok");
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) {
launch(args);
}
}
and my image is in \build\resources\main\img\h1.jpg
directory
my project files:
When I run project it gives Input stream must not be null exception.
Solution
Resource paths are not separated by \
Furthermore they start at the resource root. In this case the path "/img/h1.jpg"
should do the trick assuming your IDE properly includes the resources in the classpath at runtime.
getResource
(AsStream
) does not access the data via file path; The data may not be available as file at all, but as entry in a JAR file. If you need to refer to a file that is not included in the classpath, use File
's functionality to convert to a URI or use a FileInputStream
:
new Image(new File(".\\build\\resources\\main\\img\\h1.jpg").toURI().toString())
Answered By - fabian
Answer Checked By - Katrina (JavaFixing Volunteer)