FileNotFoundException while running as Jar - Java - java

I have written my java codes using eclipse and iam reading a file and processing the codes. The key.txt is present in the same folder as src .
BufferedReader br= new BufferedReader(new FileReader("KEY.txt"));
Now after i compile the jar and place both the jar and file in the same folder and execute iam getting FilenotFoundException. The program works if i run inside Eclipse reading the file perfectly.
The jar file and the key.txt always have to be in the same folder.
Please let me know how can I solve this issue of FilenotFoundException.

The code you have opens a file in the current working directory, which is the directory where you started the Java process from.
This is completely unrelated to where the jar file is located.
How do you execute the jar file?
If the key file is right next to the jar file, this should work:
java -jar theJar.jar
But this will not (because the path to the key is now "test/KEY.txt" ):
java -jar test/theJar.jar
When you run a program in Eclipse, the current working directory is (usually) the project root folder.
An alternative to consider (if the file does not need to be edited by the user) is to put the key file into the jar file. Then it will not get lost, and you can load it via the classloader.
Another good option is to have the user provide the path to the file, via command line parameter or system property.
Or make a batch file / shell script that makes sure that you are always running from the proper directory.

I think you should put these files with class file of the running class, because the current directory is the directory in which the class file is stored, not the source java file.

Related

Opening files located in Java jar directory, not Current Working Directory

I have a Java desktop application that I developed in NetBeans which I zip up to distribute to students. Inside this zip file I have the .jar, a "lib" directory that contains the swing-layout jar, and a directory I named "sourcefiles" that contains all the text files needed for the program.
All works fine if the jar file is double clicked, but when run from the command line (java -jar MyApp.jar), it can only find the "sourcefiles" directory if you first cd to the directory that the file is in before running the command, something that the some students forget to do. Apparently there is no way to change the current working directory from within my code. The path to "sourcefiles" is given in my code as a relative path, assuming that I am in the MyApp folder. So what can I do so that the program can be run from the command line without having to cd to the containing directory? Is there something to add this to the manifest file?
This problem is faced mostly by students using Linux, but it is the same on Mac. I assume it's the same on Windows, but I guess none of the students with Windows run it from the command line.
You can't change the default directory, but you can get the directory the Jar the class is running in and use that in your code as the base path.
String jarLocation = ThisClass.class.getProtectionDomain()
.getCodeSource().getLocation().getPath();
From this you can get the directory the jar is in. Most likely you will want to wrap this up as a method your students can call.

Building file.jar, External Executable File missing

Assuming that I use NetBeans 7.3 , I created a project that, in a nutshell, receiving as input a set of parameters, it returns as output a print on screen. The project is made up of a number of directories. Each directory contains a class (in file.class form). One of these directory contains an executable in C. I wrote it as the kernel of the Java project.
I built file.jar and I added it as a library in a new project. When I tried to test it, an error message made ​​me realize that the C written program is not was automatically added to file.jar under construction.
One of my first attempt to solve this problem was to manually add the C-executable file. By using the JAR command from the terminal on my Mac, I was able to update the file.jar adding the executable in the right subfolder.
This solution is not served because, moving from project to file.jar, the relative path that leads to the execution of the C-program has changed. So I tried to change this path seeing it from the point of view of file.jar. Yet this attempt was futile.
I defer to those with more experience than me in the packaging and distribution of Java content.
As far as I know, an operating system cannot directly execute an executable that is inside a zip file (which is what a jar file actually is). It has to be first extracted.
So your program could first open its own jar file and extract the executable file into a file on disk, then run that file.
You can create an installer program, to install both the jar file and the executable file to a suitable location on the user's disk.

Reading file from within JAR not working on windows

I'm trying to read from a file that is packaged up inside a JAR, along with the class that reads it. To do this, I use the following:
getClass().getClassLoader().getResourceAsStream(file)
This works fine when I create and run the JAR file on OSX, but if I create and run the JAR file on windows, the above line returns null.
Am I missing something here? If I create the JAR on OSX and run it on Windows it works fine. The problem only occurs when I create the JAR on windows.
EDIT: It's worth mentioning that there is no folder hierarchy within the JAR file. Everything is stored at one level, thus the class reading the file and the file itself are both in the same directory. Additionally, this is how I'm creating the JAR file, on both OSX and Windows:
jar -cmf manifest.mf run.jar *.class file1 file2
EDIT 2: The file I am trying to load is a java .properties file. I take it that's not what is causing the issue?
Skip the classloader part. Just getClass().getResource....
Try it this way getClass().getResourceAsStream("/file1").
When using file separators, don't hard code them!
Use java.io.File.separator instead: http://docs.oracle.com/javase/7/docs/api/java/io/File.html#separator

Load files External To The Distribution Jar

I have written a Java program which I package and run from a JAR file. I need to have some user-changeable configuration files which are simply text lines of:
key = value
format. To load these files I used the class described here. When I run my program through Netbeans IDE all works fine as I have included the directory where I store the configuration files in the Project properties.
The problem comes when I build my application into a JAR file. As I want the configuration files to be user-editable I keep them OUTSIDE of the JAR but in the same directory but now when I run my application from the command line it cannot find the configuration files. If I manually add the files to JAR file at the ROOT folder then all is well.
So how can I tell Java to look outside of the JAR for my loadable files? The -classpath option has no effect.
That's because the way you are loading them requires that they be inside the .jar when running from a jar, or inside the project directory if not; it's relying on the classloader to tell it where to find the file.
If you want to open a file outside the .jar, you need to just open it as a File and read it in.
One of the ways we've approached this is to take the external filename as an option on the command line (e.g. java -jar myJar.jar -f filename). This allows you to explicitly state where the file is located. You can then decide whether or not to also look in a default location, or inside the .jar if the file isn't specified on the command line.
I resolved it by referring to this question. I Added the current directory to the MANIFEST file of the jar and it works.
Why is the -classpath option ignored in this case I wonder? Security?
I had the same problem and saw your post, but the answer in the end, was simple.
I have an application deployed via Java Webstart and am building it in Netbeans 7.3.
I have a properties file config.xml that will be updated during run time with user preferences, for instance, "remember my password".
Hence it needs to be external to the jar file.
Netbeans creates a 'dist' folder under the project folder. This folder contains the project jar file and jnlp file. I copied over the config.xml to the dist folder and the properties file was loaded using standard
FileInputStream in = new FileInputStream("config.xml");
testData.loadFromXML(in);
in.close();

Putting bat file inside a jar file

I have a java class that uses a bat file to execute commands. However I developed it in Eclipse IDE. It works fine in there. But as I export it in a jar file, it fails to find the bat file that was included.(gives me an IOException)
The file structure in eclipse is as follows
:
Project1
---->src
------>com.myproj
-------->BatFileRead.java
----md.bat
----ul.bat
md.bat and ul.bat is same level as src directory. After jarring it src folder disappears.
Could someone help me with this.
Thanks
In order to execute the command, you'll have to extract the bat file afterwards. You can't run executables which are inside jar files. Basically you'll need to open the batch file entry in the jar file as an input stream, and copy the data to a FileOutputStream on disk. You won't be able to execute it until it's a proper standalone file on the file system.
If you're already trying to extract it, chances are you're using getResource or getResourceAsStream slightly incorrectly. This is easy to do, because it depends whether you're calling ClassLoader.getResourceAsStream or Class.getResourceAsStream. The first only ever uses absolute paths (implicitly) and the second can use either absolute or relative paths. For example, in your case you'd want:
BatFileRead.class.getResourceAsStream("/md.bat")
or
BatFileRead.class.getClassLoader().getResourceAsStream("md.bat")
Have you checked that the bat files are definitely ending up in the jar file? Just list the contents with
jar tvf file.jar
to see what's in there.
Well this can be very dangerous. Be sure to use gloves when dealing with the BAT. They bite and quite painfull. Also try getting jar that has a big enough opening, although the bats will fit almost through any hole.
Good luck, and don't try this at home. This is done by professionals.
Try copying file.jar to file.zip, and opening file.zip (e.g. just double clicking, or using e.g. 7-Zip). Can you find your .bat files inside? If the .bat file isn't there, you have to add the .bat file to your Eclipse project, and rebuild in Eclipse. If the .bat file is there, but you still get an IOException opening it from you .java application, then please post the code snippet triggering the IOException, and please give a full listing of file.zip (get the listing by extracting file.zip to C:\testdir, and running dir /s C:\testdir in the command line).
Please note that Jon Skeet is right that although it is possible to open any file in the .jar file as an InputStream using java.lang.Class.getResourceAsStream and java.lang.ClassLoader.getResourceAsStream (see tutorial or find them in the Java API docs), but in order to execute a .bat file inside, you have to extract the .jar file first.

Categories

Resources