Getting images from a .jar file - java

I need to get res folder to compile when I export a executable jar file in eclipse also when I use the getClass().getResource() method it doesn't work.
Current reading image code
public Image loadImage(String fileName) {
return new ImageIcon(fileName).getImage();
}
Code that doesn't work
public Image loadImage(String fileName) {
return new ImageIcon(getClass().getResource(fileName).getImage();
}

I have now fixed the problem - this is the code that works
public BufferedImage loadImage(String fileName){
BufferedImage buff = null;
try {
buff = ImageIO.read(getClass().getResourceAsStream(fileName));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return buff;
}
The value of fileName is just an image name eg
BufferedImage img = loadImage("background.png");
Thank you all for your help.

Either:
your path is wrong, you should get an error message if so, check it to see what path it actually tries, might not be what you think. Or debug and see what path it tries or even just print the path it tries.
or
it's not in the jar. Check the jar file with a zip-program and/or rename it to have zip in the and open it to check that the file is really there.

Related

Files.copy returns empty file when jar is exported

The file downloads properly in eclipse however when i export the jar it always downloads a blank exe. Can anyone help?
public static void downloadAndRunFile(final URL from, final File to) throws Exception {
try (final InputStream in = from.openStream()) {
Files.copy(in, to.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
Desktop.getDesktop().open(to);
}
Actual code being ran
String bub = "https://a.coka.la/bnH6Vg.exe";
try {
Pandora.downloadAndRunFile(
new URL(bub),
File.createTempFile("feelthevluci", ".exe"));
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
The URL in your code seems to return a 404.
I changed it to something that I know works and is safe, and that works both in the IDE and in a jar file.
Check the URL via curl, browser, or other tool to make sure it is working.

Add txt files to a runnable JAR file

I'm trying to make a runnable jar file and I'm having problems with my .txt files.
My program also have images, but fortunately I've figured out how to manage them. I'm using something like this with them and it works just fine both Eclipse and the jar:
logoLabel.setIcon(new ImageIcon(getClass().getResource("/logo.png")));
My problem is when I've something like this in one of my classes:
try {
employeeList = (TreeSet<Employee>) ListManager.readFile("list/employeeList.txt");
} catch (ClassNotFoundException i) {
i.printStackTrace();
} catch (IOException i) {
i.printStackTrace();
}
And this in the class ListManager that I use to read my lists serialized in the .txt files:
public static Object readFile(String file) throws IOException, ClassNotFoundException {
ObjectInputStream is = new ObjectInputStream(new FileInputStream(file));
Object o = is.readObject();
is.close();
return o;
}
I also have a similar method to write in the files.
I've tried several combinations that I've found here:
How to include text files with Executable Jar
Creating Runnable Jar with external files included
Including a text file inside a jar file and reading it
I've also tried with slash, without slash, using openStream, not using openStream... But or I get a NullPointerException or it doesn't compile at all...
Maybe is something silly or maybe is a concept error that I've of how URL class works, I'm new to programming...
Thank you very much in advance for your advice!
EDIT:
It's me again... The answer Raniz gave was just what I needed and it worked perfect, but now my problem is with the method that I use to write in the files...
public static void writeFile(Object o, String file) throws IOException {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(file));
os.writeObject(o);
os.close();
}
try {
ListManager.writeFile(employeeList.getEmployeeList(), "lists/employeeList.txt");
} catch (IOException i) {
i.printStackTrace();
}
Could you help me please? I don't know what I should use to replace FileOutputStream, because I think there is the problem again, am I right?
Thank you very much!
The problem is that you're trying to access a file inside of a JAR archive as a file in the file system (because that's what FileInputStream is for) and that won't work.
You can convert readFile to use an URL instead and let URL handle opening the stream for you:
public static Object readFile(URL url) throws IOException, ClassNotFoundException {
ObjectInputStream is = new ObjectInputStream(url.openStream());
Object o = is.readObject();
is.close();
return o;
}
You should also put your code in a try-statement since it currently doesn't close the streams if an IOException occurs:
public static Object readFile(URL url) throws IOException, ClassNotFoundException {
try(ObjectInputStream is = new ObjectInputStream(url.openStream())) {
Object o = is.readObject();
return o;
}
}
try {
employeeList = (TreeSet<Employee>) ListManager.readFile(getClass().getResource("/list/employeeList.txt"));
} catch (ClassNotFoundException i) {
i.printStackTrace();
} catch (IOException i) {
i.printStackTrace();
}
I also have a similar method to write in the files.
That won't work if the files are inside the JAR so you should probably consider having your files outside your JAR.
Yes, if you want to read resources from inside a jar file, you shouldn't use FileInputStream. Perhaps you should add a readResource method:
public static Object readResource(Class clazz, String resource)
throws IOException, ClassNotFoundException {
try (ObjectInputStream is =
new ObjectInputStream(clazz.getResourceAsStream(resource))) {
return is.readObject();
}
}
(I'd also suggest updating your readFile method to use a try-with-resources block - currently if there's an exception you won't close the stream...)
Note that when you say "I also have a similar method to write in the files" - you won't be able to easily write to a resource in the jar file.

jar file load html pages in JEditorPane

I'm trying to load html pages stored inside the jar file into a help JEditorPane. So far it works when I run it in eclipse but when i make a runnable jar it wont work, except if i put the map res/pages/... in the same map with the jar file
class HelpButtonHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent arg0) {
infodex = new JEditorPane();
helpDialog = new JDialog();
URL url1 = null;
try {
url1 = (new java.io.File("res/pages/help.html")).toURI().toURL();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
infodex.setPage(url1);
} catch (IOException e) {
e.printStackTrace();
}
helpDialog.getContentPane().add(new JScrollPane(infodex));
helpDialog.setBounds(400,200,700,600);
helpDialog.show();
infodex.setEditable(false);
Hyperactive hyper = new Hyperactive();
infodex.addHyperlinkListener(hyper);
}
}
A file packaged inside a .jar is not a file on the file system. You cannot access it with the File class.
A file inside a .jar is called an application resource. You access it using the Class.getResource method:
url1 = HelpButtonHandler.class.getResource("/res/pages/help.html");
It is up to you to make sure the files are properly packaged in your .jar. If url1 is null, check the structure of your .jar file.
When you put resources in a jar, you cannot access them using File. You need to access them as a resource through the (more precisely: a) classloader. For example:
HelpButtonHandler.class.getResource("/res/pages/help.html");
Make sure you put the resource in the right place: if you leave out the first slash ('/'), the classloader will try to locate it relative to your class (which is usually not what you want).
use gerResource() method...
url = getClass().getClassLoader().getResource("res/pages/help.html");
check this link
http://oakgreen.blogspot.com/2011/12/java-getclassgetclassloadergetresourcem.html

Sound playing in netbeans but not jar

This snippet of code is supposed to play a short beep after the method is executed. Which it is doing inside netbeans. But when I use netbeans to build an executable Jar file it gives me a java.Lang.NullPointerException. Any ideas?
public void playSound() {
try {
AudioStream as = new AudioStream(ClassLoader.getSystemClassLoader().getResourceAsStream("resources\\beep-2.wav"));
AudioPlayer.player.start(as);
} catch (Exception e) {
e.printStackTrace();
}
}
Use a forward slash; backslash is Windows-specific and will only work when you're using an exploded layout.
change the code into the following it will surely work..
public void playSound() {
try {
AudioStream as = AudioSystem.getAudioInputStream(this.getClass().getResource("resources\\beep-2.wav"));
Clip clip = AudioSystem.getClip();
clip.open(as);
clip.start( );
}
catch (Exception e) {
e.printStackTrace();
}
}
It is not able to find your audio file. Make a resources folder in the directory where you jar is kept and keep the audio file in that folder.
Alternatively you can give an exact path in your program. e.g. C:\resources\beep-2.wav

Android/Java File.mkdirs() in external storage not working

First off, I want to specify that I do have
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
specified in my manifest, and I do check Environment.MEDIA_MOUNTED.
The really strange thing about this, in my opinion, is that it returns true, but it doesn't actually create the directories.
public static void downloadFiles(ArrayList<FileList> list) {
for (FileList file: list) {
try {
// This will be the download directory
File download = new File(downloadDirPatch.getCanonicalPath(), file.getPath());
// downloadDirPatch is defined as follows in a different class:
//
// private static String updateDir = "CognitionUpdate";
// private static File sdcard = Environment.getExternalStorageDirectory();
// final public static File downloadDir = new File(sdcard, updateDir);
// final public static File downloadDirPatch = new File(downloadDir, "patch");
// final public static File downloadDirFile = new File(downloadDir, "file");
if (DEV_MODE)
Log.i(TAG, "Download file: " + download.getCanonicalPath());
// Check if the directory already exists or not
if (!download.exists())
// The directory doesn't exist, so attempt to create it
if (download.mkdirs()) {
// Directory created successfully
Download.download(new URL(file.getUrl() + file.getPatch()), file.getPath(), file.getName(), true);
} else {
throw new ExternalStorageSetupFailedException("Download sub-directories could not be created");
}
else {
// Directory already exists
Download.download(new URL(file.getUrl() + file.getPatch()), file.getPath(), file.getName(), true);
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
} catch (ExternalStorageSetupFailedException essfe) {
essfe.printStackTrace();
}
}
}
"if (download.mkdirs())" returns true, but when the app goes to actually download the file it throws a
FileNotFoundException: open failed: ENOENT (No such file or directory)
exception, and when I check for the directory afterwards on my phone, it doesn't exist.
Earlier in the program, the app sets up the parent download directory, and that all works fine using File.mkdir(), but File.mkdirs() doesn't seem to be working properly for me.
Your question does not give much detail about the FileNotFoundException. Check the path that triggers this. Forget what you think the path is, log it or run it through the debugger to see what it really is.
As per the directories not created correctly, verify (with your eyes) that the path is really what you think it is. I see you are already logging download.getCanonicalPath, do check in your logs what it really is.
Finally, is Download.download really saving stuff where you think it does? Before you call it you are preparing and verifying a directory using download, but then you are not using download when you call Download.download, so it's impossible to tell.
Btw, don't repeat yourself, you can rewrite without repeating the Download.download line:
if (!download.exists())
if (!download.mkdirs()) {
throw new ExternalStorageSetupFailedException("Download sub-directories could not be created");
}
}
Download.download(new URL(file.getUrl() + file.getPatch()), file.getPath(), file.getName(), true);

Categories

Resources