Failing to load font after burning to disk - java

I have an application which has a font stored within a jar file. It is loaded with:
public Font getChessFont()
{
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream("fonts\\MERIFONTNEW.TTF");
Font toReturn;
try
{
toReturn = Font.createFont(Font.TRUETYPE_FONT, in);
}
catch (Exception e)
{
toReturn = gameInformation;
}
toReturn = toReturn.deriveFont(Font.PLAIN, squareSize);
return toReturn;
}
When running the program from Eclipse or a jar file this code loads the font sucessfuly. However, after I put the jar files into an ISO image and mount them to a disk the files fail to load. Any ideas as to what I'm doing wrong?

Apparently my comment was enough to solve this. So the question can be "answered", I have added the comment as an answer:
Resource paths usually should use forward slash (/) in the path (more like a URL) as this is platform independent.

Are the files/JARs on the disk on the classpath?

Related

IOException When Loading Java Font

I'm implementing a GUI for a chess program I'm writing for a class. To make it look polished, I want to utilize a Chess Piece Font I obtained from the internet.
The file, chess.ttf, is located at the path Chess/resources/chess.ttf. I utilize the following code per Oracle's instructions (https://docs.oracle.com/javase/tutorial/2d/text/fonts.html):
try {
File file = new File("resources/chess.ttf");
//Returned font is of pt size 1
Font font = Font.createFont(Font.TRUETYPE_FONT, file);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, file));
//Derive and return a 12 pt version:
//Need to use float otherwise
//it would be interpreted as style
return font.deriveFont(12f);
}
catch (IOException|FontFormatException e) {
System.out.println("-Font Error-");
return null;
}
However, this throws an IOException. I ran getAbsolutePath() on the file and received /Users/[me]/eclipse-workspace/Chess/resources/chess.ttf so I'm assuming the file is being loaded correctly. Does anyone know what's going wrong with my code?
edit: Problem resolved? I tried InputStreams as suggested but that didn't work, yet upon reverting my code the computer finally stopped throwing IOExceptions. Isn't code the best?
You'd better copy the ttf using build script like ant or maven /Users/[me]/eclipse-workspace/Chess/bin/resources
ClassLoader loader = Thread.currentThread().getContextClassLoader();
System.out.println(loader.getResource(".").getPath()); // for tracing the working folder only
java.io.InputStream ins = loader.getResourceAsStream("resources/chess.ttf");
//Returned font is of pt size 1
Font font = Font.createFont(Font.TRUETYPE_FONT, ins);

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.

Java Image messes up when I run the .jnlp file

I have a method that gets called at the start of my program, and it works fine when I run the jar, but when I run the jnlp file it crashes.
public void newImg(String i)
{
try
{
File file = new File(i);
img = ImageIO.read(file);
}
}
img is a bufferedImage, by the way.
Odds are the path you're giving to the file, or permissions, don't match. Put the File ctor into a try block, catch the exception, and find out what it is.
It should look something like this:
try {
File file = new File(i);
img = ImageIO.read(file);
} catch (Exception ex) {
// You probably want to open the java console, or use a logger
// as a JNLP may send stderr someplace weird.
Systemm.err.println("Exception was: ", ex.toString());
}
The code you have doesn't do anything with the exception.
You might want to look at the exceptions thread in the Java Tutorial.
update
See my comments. I just tried something and confirmed what I was thinking -- code with a try {} and no catch or finally won't even compile. if this is really the code you think you're working with, you've probably been loading an old class file; this one hasn't compiled.
$ cat Foo.java
public class Foo {
public void tryit() {
try {
File f = new File(null);
}
}
}
$ javac Foo.java
Foo.java:3: 'try' without 'catch' or 'finally'
try {
^
1 error
$
Maybe your not loading your image properly. Don't use the relative location of the file. This will be different for each OS. Your image in the JAR you should be loaded correctly like this:
URL url = this.getClass().getResource("image.jpg");
Image img = Toolkit.getDefaultToolkit().getImage(url);
This will load a file called image.jpg that is located in the same location as the class. You can also use things like File.pathSeparator if its in another location.
Use one of these two methods to load it as a resource:
http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String) http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)
Make sure you have the correct file name/path.
Make sure you have file access to the file system.

Categories

Resources