Java loading a jar & then using it's data (variables & methods & classes)? - java

I have a JFrame window that downloads a jar file & then starts it so the jar will execute inside the JFrame and show inside it too.
But the whole idea is, instead of letting users download the new jar version it will automatically grab (download) the new jar with the same launcher.
Now I don't want to let them download it many times everytime, might cause bandwidth lose etc, and instead I thought of having version checking.
Java will first check if the folder MyJar exists at the home folder of the OS, along with the jar file, if yes it will access the jar files data and check if the string version equals to the new version that I will buffer before it from the website, if not equal, download a new jar file into that folder. and then start it.
if jar version equals it will process and launch that jar.
This is the code I use currently to load form the web:
String jarURL = "http://someurl/game.jar"; // example broke the link from stackoverflow
String mainClass = "main";
ClassLoader clientClassLoader = new URLClassLoader(
new URL[] { new URL(jarURL) });
Class<?> clientClass = clientClassLoader.loadClass(mainClass);
this.loader = (Applet) clientClass.newInstance();
And I want to do something like this, for example in that jar I have a public variable named version, so I can access this.loader.getClass(main.class).version <- I know it's not done that way but just an example.
How can I do this?

Related

Specifying filepaths to subdirectories inside executable jar

I'm working on a java project and made it into an executable jar. In the jar, all the correct files are included, but when running the jar, the images don't display.
When I run the program from command line, the program is able to display everything correctly.
I believe the issue might be because of how I set up the filepaths in the code?
Here's an example of my setup:
private static String imgPath;
...
imgPath = String.format("img%d.gif", value);
...
public static ImageIcon getImageIcon() {
ImageIcon ii = new ImageIcon("content/dice/" + imgPath);
return ii;
}
//getImageIcon() is later called by another class
This setup works unless I try to run the program from an executable jar. So my question is how do I get it to work from a jar?
The first mistake is assuming there is a file system (directories & such) inside a Jar. There are paths to resources that might look like directories & files, but no directories or files as such.
Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An embedded-resource must be accessed by URL rather than file. See the info. page for embedded resource for how to form the URL.

How to create a runnable jar that uses files and images as

I want to understand the best or the standard technique to write a java project when using internal files. To be precise, I want to develop a project that uses text files and images that are needed when the program runs. My goal is to create a runnable jar from the project in which the user does not need to see all these files. Therefore, I decided to create a package called resources and put it inside the folder that contains the source codes. I.e. it is in the same level as other packages. Now, in my codes when I want to use the images I use the following statement:
URL url = getClass().getResource("/resources/image1.gif");
It is working!
Then, to open a text file for reading/writing, I use the following:
String filename= "/resources/"+file1.txt;
Now, this is not working and it complains that it cannot find the file. I am not sure how to go about this?
A google search suggested that I put the resources folder on the project root directory. It is working then but when I created the runnable jar I had to put the resources folder on the same directory as the jar. This means that the user can have access to all the files in there. Any help is much appreciated.
You can use the getResource method for files too.
URL url = getClass().getResource("/resources/file1.txt");
try {
File f = new File(fileUrl.toURI());
} catch (URISyntaxException e) {
//dealing with the exception
}

Finding a resource in Java

I am developing a Java application which displays a big amount of images. The problem is I can't figure out how to make Java find these images.
I have followed several tutorials and answers here at Stackoverflow, but I still haven't managed to find a solution that works regardless of OS (Linux or Windows) and running method (embedded on eclipse or exported jar file). This might be due to the fact that I am still a newbie, though.
I have created a class, which I call myIcon and through this class I mean to access all of these images. In the following code, I want to pass the string "resources/icon/image.gif" to the function getIconPath. The output should be a ImageIcon of this image, since this file exists. Despite that, if I pass to this function the path to an image that doesn't exist, null should be returned. In this case, my application will display a default image (a red x).
public class MyIcon {
// some other functions and properties
private static final ImageIcon getIconPath(String path) {
File f = new File(path);
if (f.exists()) {
return new ImageIcon(path, "");
} else {
return null;
}
}
}
The resources folder is a sibling to the src folder in my directory structure. That is, both resources and src are subfolders of the root directory.
When I run the code above, no image is ever found. The default image is thus always displayed and getIconPath returns null.
I am also aware of the getResource method of ClassLoader, but I still don't really understand how these things should be used.
While running in eclipse, you should print out f.getAbsolutePath(). It probably doesn't point to your file. More generally, you want to access the file as a resource. See:
https://docs.oracle.com/javase/tutorial/deployment/webstart/retrievingResources.html
There are two parts to this - making sure that when you build a jar, the images are part of it, and accessing a resource within the jar.
For the first part, I am guessing that whatever you're using to build a jar, it will put your images into the META-INF folder, which should work without too much issue (if its not there, or in with the Java class/source in the generated jar, that might cause the lookup to fail)
There is another Stack Overflow Post for the second part. The key is to make sure the images you want to load are on the classpath.
Hope this helps!
If resources is in classpath, you can find for the image at classpath, using getResource(String name) or getResourceAsStream(String name).
However, in a simple Java Project, even adding resources to build path, like this:
it will just put the folder content, in other words, just icon/..., to bin folder, something like this:
So, since resources isn't in classpath, just icon, to retrieve the images, you'll need to inform as path only /icon/image.gif, like this:
URL url = YourClass.class.getResource("/icon/image.gif");
ImageIcon icon = new ImageIcon(url);

Jar File and file Dependency

I have to write a Java Project with a Swing GUI and some smaller formal requirements like a button which does something or methods which implement something, very basic.
I have written a programm with a basic GUI including a Jtable which stores information about students(name,semester...) in a Java File.
The Problem is that the path of this java-File in my programm is relative, in my case:
public static final String pfad = "src/abgabe/";
public static final String name = "Uni";
File file = new File(pfad + name)
If I export my Programm to JAR and send it around, it wont work on other computers because only I have the Java File.
Can I change my code to make the Jar File creates a new Java file in its own root directory?
Can I change my code to make the Jar File creates a new Java file in its own root directory?
Even if you can, you shouldn't. Most OS manufacturers have been saying for years that application data should not be stored in the apps. installation directory.
Instead put the file in a sub-directory of user.home. That will be a path that:
Is reproducible.
The app. should have write permissions for.
Although the question is not directly related, the answer is, so see also How can an app use files inside the JAR for read and write?

In netbeans, how to save or access an image after deploying jar file

I am trying to make a mess management application in Java using NetBeans. I want to save images of Members in a specified folder inside my src directory. I just created folder named EmpImgs for storing employees images. Here is my code:
File srcDir = new File(file); // current path of image
File dstDir = new File("src\\J_Mess_Mgnt\\EmpImgs\\"+Txt_C_G_M_M_ID.getText());
objm.copyFile(srcDir, dstDir);` // copy image from srcDir to dstDir
Here I use another class for copying images to predefined folders and renaming the images based on their ID.
Everything is working properly in Java IDE.
But unfortunately after making an executable .jar file, this code will not work. I cannot save or access any image file in that directory.
I just went through this site, but I didn't find a suitable answer.
All I need is saving and editing images inside jar folder
Hehe hi mate you need some help. This is a duplicate but I will cut you some slack and maybe you should delete this later. So back to basics, the jvm runs byte code, which you get from compiling java source code to .class files. Now this is different to C and C++ were you just get a .exe. You don't want to give your users a bunch of .class files in all these folders which they can edit and must run a command on the command line, but instead give them what is known as an 'archive' which is just an imutable file structure so they can't screw up the application, known as a jar in java. They can just double click on the archive (which is a jar), and the jvm will call the main method specified in the MetaInf directory (just some information about the jar, same as a manifest in other programming languages).
Now remember your application is now a jar! It is immutable! for the resasons I explained. You can't save anymore data there! Your program will still work on the command line and in IDEs because it is working as if you used your application is distrubuted as bunch of folders with the .class files, and you can write to this location.
If you want to package resources with your application you need to use streams (google it). BUT REMEMBER! you cant then save more resources into the jar! You need to write somewhere else! Maybe use a user.home directory! or a location specified from the class path and the photos will be right next to the jar! Sometimes you might need an installer for your java application, but usually you don't want to create the extra work if you don't need to.
At last I find an answer suit for my question.It is not possible to copy images or files to a executive jar folder.So I used a different Idea.Create some folders(as per our requirement),Where my executable jar folder is located(No matter which drive or where the location is).The code is..
String PRJT_PATH=""; //variable to store path of working directory.
private void getdire() throws IOException{
File f=new File(".");
File[] f1=f.listFiles();
PRJT_PATH=f.getCanonicalPath(); //get path details.for eg:-E:/java/dist
}
private void new_Doc_folder(){ //function for creating new folders
try{
String strManyDirectories="Docs"+File.separator+"Bil_Img"; //i need to create 2 folders,1st a folder namedDocs and In Docs folder another folder named Bil_Img
String SubDirectories="Docs"+File.separator+"EmpImgs"; //same as above but keep in mind that It will not create a Same folder again if already exists,
// Create one directory
boolean success = (new File(strManyDirectories)).mkdirs(); //create more than one directory
boolean success1 = (new File(SubDirectories)).mkdir(); //Creates a single directory
if (success && success1) {
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
It works Successfully.
Regds

Categories

Resources