Java jar not reading files from the jar, only external folders? - java

When ever I make a JAR, the JAR won't read the folder inside it, only a folder in the folder the JAR is it. OK, that wasn't very descriptive. So here is a photo I edited to support.
I hope you get the idea now. So how would I fix this? I already have res and stats part of the build path in eclipse, now what?
Code I use to read the resources:
Image player;
player = new ImageIcon("res/player.png").getImage();

When using ImageIcon and passing it a String, it expects that the parameter refers to a File.
From the JavaDocs
Creates an ImageIcon from the specified file. ... The specified String
can be a file name or a file path
Files and "resources" are different things.
Instead, try using something more like...
new ImageIcon(getClass().getResource("res/player.png"));
Assuming that res/player.png resides within the jar in side the res directory.
Depending on the relationship to the class trying to load the resource and the resource's location, you may need to use
new ImageIcon(getClass().getResource("/res/player.png"));
instead...
Updated
Some recommendations, as EJP has pointed, you should be prepared for the possibility that the resource won't be found.
URL url = getClass().getResource("/res/player.png");
ImageIcon img = null;
if (url != null) {
img = new ImageIcon(url);
}
// Deal with null result...
And you should be using ImageIO.read to read images. Apart from the fact that it supports more (and can support more into the future) image formats, it loads the image before returning and throws an IOException if the image can't be read...
URL url = getClass().getResource("/res/player.png");
ImageIcon icon = null;
if (url != null) {
try {
BufferedImage img = ImageIO.read(url);
icon = new ImageIcon(img);
} catch (IOException exp) {
// handle the exception...
exp.printStackTrace();
}
}
// Deal with null result...

Related

How to get .jar resources path?

I'm using a custom method to get pictures from the resources/ folder. The hardcoded path works well when programming during production (src/main/resources/). However when delivering, I would need to make this path relative to the .jar root. So I made this.
public static Image getImageFromFile(String file)
{
Image image = null;
try
{
String path = FileUtils.class.getClassLoader().getResource(file).toExternalForm();
System.out.println(path);
File pathToFile = new File(path);
image = ImageIO.read(pathToFile);
}
catch (IOException ex) {ex.printStackTrace();}
return image;
}
file:/C:/Users/Hugo/Desktop/Hugo/Java%20Workspace/ClashBot/bin/main/icons/level-label.png
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(Unknown Source)
at com.lycoon.clashbot.utils.FileUtils.getImageFromFile(FileUtils.java:55)
The printed path is valid and points to the corresponding picture. However, the program raises an IOException.
Why can't it find the file?
You're jumping through way too many hoops. It's quite simple:
FileUtils.class.getResource("path.png");
// -OR-
try (var in = FileUtils.class.getResourceAsStream("path.png")) {
// in is an inputstream.
}
is all you need. Note that this means the path.png file is searched for in the exact same place (and even same 'subdir') as where FileUtils lives. So if you have, say, a file on C:\Projects\Hugo\MyApp\myapp.jar, and if you were to unzip that, inside you'd find com/foo/pkg/FileUtils.class, then the string path.png would look in that jar, and for com/foo/pkg/path.png. In other words, AnyClass.class.getResource("AnyClass.class") will let a class find its own class file. If you want to go from the 'root' of the jar, add a slash, i.e. FileUtils.class.getResource("/path.png") looks in the same jar, and for /path.png inside that jar.
getResource returns a URL. getResourceAsStream returns a stream (which you need to close; use try-with-resources as I did). Just about every resource-using API out there will take one of these two as input. For example, ImageIO does so; it even takes a URL so you can use either one:
var image = ImageIO.read(FileUtils.class.getResource("imgName + ".png"));
Yes. It's a one-liner. This will load images straight from within a jar file!
You could try to use a slightly different call like this:
java.net.URL fileUrl = Thread.currentThread().getContextClassLoader().getResource(file);
String filePath = URLDecoder.decode(fileUrl.getPath(), "UTF-8");
image = ImageIO.read(filePath);

Deploying images used in Java Application with the built jar file

After using images for example on a Button, when I build the application creating the .jar file and execute only the file, the images are not there but would only show if I copy the images folder in the same directory as the jar file. Why is that and how can I resolve this if possible?
I am currently using the following code to set the icon/image:
JButton btn = new JButton("Text", "img/icon.png");
The fact that you can use the images when they are stored outside the jar, suggests that you are doing something of the kind:
File image = new File("directory/image.jpg");
InputStream is = new FileInputStream(image);
This reads a file from a directory on the file system, not from the classpath. Now, if you have packaged your image in a "directory" inside your Jar, you must load the image from the classpath.
InputStream is = getClass().getResourceAsStream("/directory/image.jpg");
(note the slash in the path)
Or
InputStream is = getClass().getClassLoader().getResourceAsStream("directory/image.jpg");
(note the absence of the slash in the path)
Your example, as it is now, should not compile. (The second argument of your JButton construtor is an Icon, not a String, java 8). So when you were getting the image from the file system, you were probably doing something else.
With your example, you need to read an image from the inputstream and convert it to an Icon:
try (InputStream is = getClass.getClassLoader().getResourcesAsStream("directory/image.jpg")) {
BufferedImage image = ImageIO.read(is);
return new JButton("Text", new ImageIcon(image));
} catch (IOException exc) {
throw new RuntimeException(exc);
}
That should use the image that is located in "directory" inside your jar. Of course, you need to include the image within your jar, or you will get a NullPointerException on the inputstream is.
I think you need to understand the
ClassLoader:
A typical strategy is to transform the name into a file name and then
read a "class file" of that name from a file system.
So with this you will be able to lead Resources of your project with getResource
public URL getResource(String name)
Finds the resource with the given name. A resource is some data
(images, audio, text, etc) that can be accessed by class code in a way
that is independent of the location of the code.

Java, display chm file loaded from resources in jar

I am trying to display the chm file containing the help which is loaded from resources:
try
{
URL url = this.getClass().getResource("/resources/help.chm");
File file = new File(url.toURI());
Desktop.getDesktop().open(file); //Exception
}
catch (Exception e)
{
e.printStackTrace();
}
When the project is run from NetBeans, the help file is displayed correctly.
Unfortunately, it does not work, when the program is run from the jar file; it leads to an exception.
In my opinion, the internal structure of jar described by URI has not been recognized... Is there any better way? For example, using the BufferReader class?
BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream()));
An analogous problem with the jpg file has been fixed with the BufferedImage class
BufferedImage img = null;
URL url = this.getClass().getResource("/resources/test.jpg");
if (url!= null)
{
img = ImageIO.read(url);
}
without any conversion to URI...
Thanks for your help...
A .jar file is a zip file with a different extension. An entry in a .jar file is not itself a file, and trying to create a File object from a .jar resource URL will never work. Use getResourceAsStream and copy the stream to a temporary file:
Path chmPath = Files.createTempFile(null, ".chm");
try (InputStream chmResource =
getClass().getResourceAsStream("/resources/help.chm")) {
Files.copy(chmResource, chmPath,
StandardCopyOption.REPLACE_EXISTING);
}
Desktop.getDesktop().open(chmPath.toFile());
As an alternative, depending on how simple your help content is, you could just store it as a single HTML file, and pass the resource URL to a non-editable JEditorPane. If you want to have a table of contents, an index, and searching, you might want to consider learning how to use JavaHelp.

Absolute Path of a Local File Object

so I'm looking towards porting a .jar to an executable and am cleaning my code up a bit before I do that. Right now I have the following:
BufferedImage bgImg = null;
//Grabs the background image
try {
bgImg = ImageIO.read(new File(""));
} catch (IOException e1) {
e1.printStackTrace();
}
I have several other images that I can just use:
new ImageIcon(getClass().getResource("imagename.png")));
However, since the former is a File object it does not take the same type of argument. I was wondering if there is something similar that I can use for that, or if there is some other way to make the File absolute so that there are no errors when porting to an executable. Thanks!
Use the read(InputStream input) method instead with Class.getResourceAsStream().
For example:
bgImg = ImageIO.read(getClass().getResourceAsStream("imagename.png"));
I'm not sure what you want to do. But you can access a file in your current working directory with a dot before the path.
E.g.
ImageIO.read(new File("./imagename.png"));

How to access resources in JAR file?

I have a Java project with a toolbar, and the toolbar has icons on it. These icons are stored in a folder called resources/, so for example the path might be "resources/icon1.png". This folder is located in my src directory, so when it is compiled the folder is copied into bin/
I'm using the following code to access the resources.
protected AbstractButton makeToolbarButton(String imageName, String actionCommand, String toolTipText,
String altText, boolean toggleButton) {
String imgLocation = imageName;
InputStream imageStream = getClass().getResourceAsStream(imgLocation);
AbstractButton button;
if (toggleButton)
button = new JToggleButton();
else
button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(listenerClass);
if (imageStream != null) { // image found
try {
byte abyte0[] = new byte[imageStream.available()];
imageStream.read(abyte0);
(button).setIcon(new ImageIcon(Toolkit.getDefaultToolkit().createImage(abyte0)));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
imageStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else { // no image found
(button).setText(altText);
System.err.println("Resource not found: " + imgLocation);
}
return button;
}
(imageName will be "resources/icon1.png" etc). This works fine when run in Eclipse. However, when I export a runnable JAR from Eclipse, the icons are not found.
I opened the JAR file and the resources folder is there. I've tried everything, moving the folder, altering the JAR file etc, but I cannot get the icons to show up.
Does anyone know what I'm doing wrong?
(As a side question, is there any file monitor that can work with JAR files? When path problems arise I usually just open FileMon to see what's going on, but it just shows up as accessing the JAR file in this case)
Thank you.
I see two problems with your code:
getClass().getResourceAsStream(imgLocation);
This assumes that the image file is in the same folder as the .class file of the class this code is from, not in a separate resources folder. Try this instead:
getClass().getClassLoader().getResourceAsStream("resources/"+imgLocation);
Another problem:
byte abyte0[] = new byte[imageStream.available()];
The method InputStream.available() does not return the total number of bytes in the stream! It returns the number of bytes available without blocking, which is often much less.
You have to write a loop to copy the bytes to a temporary ByteArrayOutputStream until the end of the stream is reached. Alternatively, use getResource() and the createImage() method that takes an URL parameter.
To load an image from a JAR resource use the following code:
Toolkit tk = Toolkit.getDefaultToolkit();
URL url = getClass().getResource("path/to/img.png");
Image img = tk.createImage(url);
tk.prepareImage(img, -1, -1, null);
The section from the Swing tutorial on How to Use Icons shows you how to create a URL and read the Icon in two statements.
For example in a NetBeans project, create a resources folder in the src folder. Put your images (jpg, ...) in there.
Whether you use ImageIO or Toolkit (including getResource), you must include a leading / in your path to the image file:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/resources/agfa_icon.jpg"));
setIconImage(image);
If this code is inside your JFrame class, the image is added to the frame as an icon in your title bar.

Categories

Resources