Where does .jar file look for input files? - java

I create a .jar file on my local computer (with ant/eclipse) then upload it to a server (foo/usr/share/java). I want my .jar file to read in a file called "example.txt". Where on my server do I need to save "example.txt" so that this happens? Alternatively, how should I alter the filepath in my code? I am happy hardcoding this one filepath as neither the file nor filepath will change. Thanks!

If you running your application at console, then save your text file at current folder. If your application works inside application server, then file will be searched in current folder of application server.
Best way to open exact file you need - use program argument.
In the Java programming language, every application must contain a main method whose signature is:
public static void main(String[] args)
This array is the mechanism through which the runtime system passes information to your application. For example:
java MyApp arg1 arg2
Each string in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it.

If you supply a relative pathname, it is relative to the user's current working directory when he executed the .jar file. If you provide an absolute filename, job done.

You should put the file in the same directory as your .jar file and your program should find it, but as chrylis mentioned, a command-line argument is the best.

Related

How can I get the path of the compiled jar file via code?

I want to use image files for my java program, and for that I need File objects. But I have the problem that when I build my project, the project name has a .jar at the end of the name, making a File object like new File("..\\Project\\src\\ImageDirectory\\Image.png") useless, since the directory doesn't exist.
I've found out I could tecnically iterate through all the directorys on the computer but I don't want to do that because that could take some time with high amounts of directories and harddrives.
So, is there a reliable and easy way to get the directory the jar file is currently in?
My IDE is InellijIDEA
You can use Path to do this:
Path path = Paths.get(YourMainClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());
Path have several methods to get more information.
For example, i have this JAR in Desktop and i am printing this:
System.out.println(path);
System.out.println(path.getRoot());
System.out.println(path.getParent());
The results are:
java -jar C:\Users\gmunozme\Desktop\Test.jar
C:\Users\gmunozme\Desktop\Test.jar
C:\
C:\Users\gmunozme\Desktop
Check that out,
Hope you can use it.

AbsolutePath not found when executing the JAR file but it works from the IDE [duplicate]

I need to add an exel file into my jar so it's portable. I know the answer is using getClass().getResource.... but i don't have a clue on how to go about using this code.
I have the exel file in the src folder with my class files, it works in netbeans but not when i open the jar file on another PC. i get filenotfound exception
here is the code i have used:
public class WindageLogic {
//....
public void GetValues() throws Exception
{
File exel=new File("src/Calculator/table1.xls");
Workbook w1; //reads from file
//reads from file
w1 = Workbook.getWorkbook(exel);
Can someone give me the code to implement which will allow me to access this file from the jar application, I've spent all weekend looking up stuff on the internet but i don't understand how i can use these getresource techniques.
thanks alot
If your excel file is a resource, then you can't use File to manipulate it but rather resources, and I believe that it is read-only -- are you sure that this is what you want to do? You could instead load a command line String that tells the program where to start looking for the file, or create a property file that tells where to first look.
Edit 1
If you are using JExcel then you can call Workbook.getWorkbook(java.io.InputStream is) and get your resource as a Stream via Class's getResourceAsStream(...) method.
e.g.,
public void GetValues() throws Exception {
Workbook w1; //reads from file
w1 = Workbook.getWorkbook(WindageLogic.class.
getResourceAsStream("/Calculator/table1.xls") );
//...
In order for the getClass().getResource() method to work the resource should be available in the classpath of the application (either packed in one of the jar files or simply on a folder on disk that is included in the classpath).
Depending on what IDE or code building tool you are using there are multiple ways of making sure it's done.
The simplest way is to put the src folder in the run classpath java -classpath src:%CLASSPATH% <your.class.name>

Getting the current user's path rather than application path in java

I am trying to get the current users path in a giant command line application that has multiple dependencies. Every time a "." is used, it gives me the application path (where the jar exists), rather than the current user path(where the call is being made).
So, when this is ran:
File file = new File(".");
System.out.println(file.getCanonicalPath());
Gives me the path that the application exists in.
But when I create a separate small application, and use the same code. Call the jar from a different directory, it gives the current user path.
I am using JSAP command line parser for the command line arguments, its acting the same way. How can this be solved? I want my big application to get the current user path, not application path.
What would cause them to behave differently?
I think you'll find that the batch file (/shell script) which launches your "big application" is changing directory to the main jar file's directory before kicking off Java, which is why your simple test application returns the user's working directory for new File(".") while the big app returns the jar file's directory.
Try storing the user's CWD early in the batch file and then passing it to Java:
set savedcwd=%cd%
... later on ...
java "-Dsavedcwd=%savedcwd%"
then in your application
String savedcwd = System.getProperty("savedcwd");
http://www.mindspring.com/~mgrand/java-system-properties.htm
you want "user.home" property, like
System.getProperty("user.home");
String currentDir = new File(".").getAbsolutePath();
OR
System.getProperty("user.dir")
1) As stated above, if you want to get "current directory", one way is to use File(".").getAbsolutePath()
2) If you want to get the user's $PATH variable (or any environment variable), use System.getenv():
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html

Delete a file across multiple operating systems

So I have a program that runs something like the following
public class SHandler extends Handler {
File lmpFile;
Down later in the program:
lmpFile = new File("Stuff.zip"); // This should create a file called "stuff.zip" in the present directory
OutputStream fos = new FileOutputStream(lmpFile); // Fill the file with whatever
Then from my main I call
S.SHandler SpecialSH = new S.SHandler(args);
//use the object for whatever
SpecialSH.delFile();
Delfile is made like this and is a method inside the class:
public void delFile() {
lmpFile.deleteOnExit();
lmpXMLFile.deleteOnExit();
}
To my knowledge this program works right on my local machine (Windows 7 Enterprise), however on our development box when I run this it's tossing a LOT of files that the program pulls all over the place. The execution path is /usr/data/dev/Handler and it's putting "stuff.zip" (and the files extracted from it) in /etc/cron.d and despite trying to remove them I am unable to.
Note This program is being called via a bash script which is invoked by a cron job on a machine running RHEL6. Anyone able to help this would get my undying love and appreciation.
Edit: The bash script is simply:
export JAVA_HOME=/usr/data/java/current
export PATH=$JAVA_HOME/bin:$PATH
/usr/data/java/current/bin/java -jar /usr/data/dev/Handler/Handler.jar
Tl;DR: File runs fine on windows, when RHEL6 calls a cron, files end up where they shouldn't. How can I make my program handle this?
It looks like the working directory is /etc/cron.d/ (executable path is different).
Relative paths (when using java.io.File), are relative to the working directory. If you want your files placed in a different directory, use absolute file paths: /path/to/stuff.zip (note the leading slash).
Perhaps these files are not closed, when delete occurs, or perhaps, an other program use them ?

Creating a standalone package in java and take some settings from the configuration file

Anyone plz let us know what to do when we have some configuration file which is basically xml.I want to for example give the path to save the image(for my java program) in a folder from some config file (xml in my case).In that case where should the config file be kept.Rt now every thing is converted to jar file when i create a java standalone package.But i want to give some setting from xml file.What to do in that case.How is it possible.This article only provides to create a single jar file for java project but talks nothing about the configuration settings that u can provide from some external source.
Regards
Sagar
I'm not sure I fully understand your question, but if it is where to put the XML file with configuration information, you can place your xml file in the same directory as your jar file, and then pass the XML file name and path into the Jar on the command line when calling the Jar. If you're running it in Windows, this is often done using a shortcut. Then you can get the full path string for the Jar from the main method's String[] arg array that accepts the command parameters.
Sagar,
The fact your java program is a standalone package (.jar file) has no bearing on where your configuration file is stored. Your java package is a program and that program can read any file from the file system that it so desires; it does not have to be part of the code inside the IDE i.e. you don't have to write it when you write the program. What you do need is some way, when you start the program, to find and read said configuration file.
Depending on how you expect the program to be configured, you might put that file in a number of locations. For example, /etc/yourimageprogram/config.xml or c:\program files\yourimageprogram\config.xml or perhaps c:\users\Sagar\Application Settings\yourimageprogram\config.xml. Which you choose of those options really depends on what the use case is and that I can't help with.
However, there are some main points to reading any file:
Does it exist?
Are we allowed to open it for reading?
Are we allowed to open it for writing? Might want to know if we want to update the config?
In Java, typically, you would test this with:
File configfile = new File("C:\test.xml");
if ( configfile.exists() && configfile.canRead() )
{
// read the file
}
else
{
// decide what to do if no config exists.
// might be first run of app.
}
The next stage is to parse the file. There are a number of parsers available for XML including sax and org.w3c.dom. What you need to do is to use these to extract the information you require and store that in a class. Probably a singleton class as you're unlikely to have multiple configuration instances per instance of the program.
I suggest you read about XML Parsers and File Handling under Java. Also look at the File object. See all your options for file io in java. These should give you some indication of how to proceed.

Categories