Why getClass().getResourceAsStream(file.getAbsolutePath()) throws nullPointerException? - java

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.

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.

Related

JavaFX: ImageView cannot load image that was created by the program itself. Error: java.lang.IllegalArgumentException:

I am attempting to create a program in which the user selects an image from a different folder on their computer and JavaFX copies that image into the project directory for future use. A new folder is created that will store the newly created image file. This is essentially the code for selecting and copying the image into the project directory:
Stage window = (Stage) ap.getScene().getWindow();
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select Image File");
File selectedFile = fileChooser.showOpenDialog(window);
//Creates a new directory for the new calendar that the user wants to create
File file = new File("src/DefaultUser/" + nameField.getText() + "/");
file.mkdir();
//Creates a new file name with logo as the name, but keeping the extension the same
int index = selectedFile.getName().lastIndexOf(".");
String ext = selectedFile.getName().substring(index);
//Stored in newFileName
String newFileName = "logo" + ext;
File newFile = new File(file.getPath() + "/" + newFileName);
//Copies the selected file into the project src folder, with newFileName as the new file name
Files.copy(selectedFile.toPath(), newFile.toPath());
Then the program moves onto a different scene and thus a different controller actually loads the image into an ImageView. I know that the path for the Image works properly but for whatever reason the program cannot find the image file to load it into the ImageView.
Here is essentially the code used for that:
image.setImage(new Image("DefaultUser/" + imagePath));
Don't worry about what imagePath is in this case because I am absolutely positive it paths to the correct location for the newly created image file. This is because if I close the JavaFX program and rerun it, the image loads properly.
At first, I thought it was because it took time for the image to be copied into the project directory but I checked that the file actually existed within the code and it did so this is apparently not the case. I tried using Thread.sleep() to delay the program a bit so that the code would potentially have more time to copy the file but it still threw the same error: java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found
The strangest part about this is that the program works perfectly fine, it's just that I have to restart the JavaFX program for it to be able to detect the image file, even though I know it exists. Is there something weird about JavaFX and creating new files and accessing them within the same program? I am truly lost. Thank you so much in advance for any help and I'm sorry if this doesn't give enough information because I don't want to have to explain the whole project.
Just like haraldK and James_D said in the comments putting stuff in the src folder is generally a bad idea. I solved the issue by moving the folder out into the project directory instead.

load an image from project's folder in java

I want to load an image which is in my projet folder as : /src/images/URL.jpg
I tried this code :
BufferedImage image = ImageIO.read(getClass().getResource("/images/URL.jpg"));
But I'm getting this error :
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1388)
at Personel.PersonnelMainForm.print(PersonnelMainForm.java:464)
How can I solve this problem ?
From personal experience I use:
BufferedImage image = ImageIO.read(getClass().getResourceAsStream("/images/image.jpg"));
I get the resource as a stream and that seems to work fine for me.
You can try this version of read, which takes File as an argument.
BufferedImage image = ImageIO.read(new File("path"));
where path is the path to you file, absolute or relative as you need.
Another option, if you really want to load it as a resource, would be editing your classpath, as per this question.
I suppose you have a java class in the package.
You have to move up so many times as package levels.
Example:
Java class is defined as org.test.MyClass
you have to go up twice (../../) to be in the main directory.

Loading an image from the Resource Folder

The code I am using to load the image is:
ImageIO.read(SpriteSheet.class.getResource(path));
The path being the path to the resource. But it would error with IllegalArgumentException. I wondered what might be causing and came to the conclusion that the resource should be added into the same path as the class.
Is it possible to load the image from another folder, like a res folder outside of the bin folder? (folder holding compiled classes)
EDIT:
So i messed around with a few things, and came to a solution. But now I have another problem. Here is my code
File sheet = new File(SpriteSheet.class.getProtectionDomain().getCodeSource().getLocation().getPath());
URI uri = sheet.toURI();
BufferedImage image = ImageIO.read(uri.toURL());
When I try to run it, it gives me an IIOException: Can't read Input File
This means that I can never actually get it work. I tried debugging by prining the URL to the console and this is the URL.
C:\Users\Amma\Abhijeet\Eclipse%20Workspace1\Test%20Game\bin
The %20 comes in the middle. Meaning that the file is and never can be acceesed. Is there anyway I can fix this?
Thanks.
Class.getResource will return null if the resource could not be found or the invoker doesn't have adequate privileges to get the resource.
All variants of ImageIO.read will throw an IllegalArgumentException if they receive a null input.
Take a look at the documentation of the getResource to understand how an absolute resource name is constructed from the given resource named and what are the rules for searching resources.
You can read images from any location as long as you have permissions to do so, the ImageIO.read method accepts a File, URL or InputStream so you have many option to do it.

FileInputStream and FileNotFound Exception

I am trying to retrieve a jrxml file in a relative path using the following java code:
String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";
File report = new File(jasperFileName);
FileInputStream fis = new FileInputStream(report);
However, most probably I didn't succeed in defining the relative path and get an java.io.FileNotFoundException: error during the execution.
Since I am not so experienced in Java I/O operations, I didn't solve my problem. Any helps or ideas are welcomed.
You're trying to treat the jrxml file as an object on the file-system, but that's not applicable inside a web application.
You don't know how or where your application will be deployed, so you can't point a File at it.
Instead you want to use getResourceAsStream from the ServletContext. Something like:
String resourceName = "/WEB-INF/reports/MemberOrderListReport.jrxml"
InputStream is = getServletContext().getResourceAsStream(resourceName);
is what you're after.
You should place 'MemberOrderListReport.jrxml' in classpath, such as it being included in a jar placed in web-inf\lib or as a file in web-inf\classes.
The you can read the file using the following code:
InputStream is=YourClass.class.getClassLoader().getResourceAsStream("MemberOrderListReport.jrxml");
String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";
Simple. You don't have a /web/WEB-INF/reports/MemoberOrderListReport.jrxml file on your computer.
You are clearly executing in a web-app environment and expecting the system to automatically resolve that in the context of the web-app container. It doesn't. That's what getRealPath() and friends are for.
check that your relative base path is that one you think is:
File f = new File("test.txt");
System.out.println(f.getAbsoluteFile());
I've seen this kind of problem many times, and the answer is always the same...
The problem is the file path isn't what you think it is. To figure it out, simply add this line after creating the File:
System.out.println(report.getAbsolutePath());
Look at the output and you immediately see what the problem is.

Java getClass().getResource("file") leads to NullPointerException

I am following the Snake Java games tutorial and always get this error:
ImageIcon iid = new ImageIcon(this.getClass().getResource("ball.png"));
ball = iid.getImage();
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at snake2.Board.<init>(Board.java:52)
at snake2.Snake.<init>(Snake.java:10)
at snake2.Snake.main(Snake.java:22)
I actually just copied and pasted the code to see how it works. They are in the right packages too; but when I try to run it, I always end up with this error.
The image should be in the same package (folder in OS terms) as the compiled class. Check whether you have both .class and .png in the same folder. If not, you can use classpath-relative paths in getResource(..), by starting with /
Try this:
ImageIcon iid = new ImageIcon(this.getClass()
.getClassLoader().getResource("ball.png"));
ball = iid.getImage();
Make sure image is in the same folder as java file.
Try using System.out.println(System.getProperty("java.class.path")); to find out location of your .class file and place the images in this folder.
It is general risky to load resources using relative paths, I'd always recommend using absolute paths, so do
/ball.png
if the the image is at the root of your classpath, or add a path to the location.
You have to put the image file(ball.png) into your classpath. More details, please take a look at the Javadoc.
if the resource is in your classpath then you should be trying "this.getClass().getClassLoader().getResource("ball.png")". For you actual code to work, the ball.png needs to be in the location where your .class file is (i.e., inside the package).
Go to project >clean in the eclipse it would refresh the package explorer and you won't face this problem anymore.
You may need to add the file to your build resources, something like this:
<build>
<resources>
<resource>
<directory>path\to\resources</directory>
<includes>
<include>ball.png</include>
</includes>
</resource>
</resources>
You can use only path of your image. I think this will help you:
Use this:
ImageIcon iid = new ImageIcon("C:\\Users\\ranig\\My\\spaceinvaders\\ball.png");
Note: C:\\Users\\ranig\\My\\spaceinvaders\\ball.png is the whole path of ball.png image.
instead of this:
ImageIcon iid = new ImageIcon(this.getClass().getResource("ball.png"));
Note: If u want to only try snake code and only want to get output.
I will make it simple for you . Here is an example:
Icon bug = new ImageIcon(getClass().getResource("bug1.png"));
here "bug1.png" is the resource and if it is unavailable then it can cause error as you have discussed here.
Import an image to the same directory in which your program resides.
You can also give whole path to it as well
ImageIcon(getClass().getResource("C://me/file/bug1.png"));
The resource so named wasn't found. It needs to be in the same directory as the .class file you are calling it from. See the Javadoc.

Categories

Resources