Access a file from a JAR in the same folder - java

I need to acces (create and read) a file from a JAR file (executable jar),
and that file should be created in the same directory as the JAR
I tried
this.getClass().getResource("myFile")
but since the jar has packages in it, it won't work..
I also tried write just
File f = new File("myFile");
f.createNewFile();
and that works if i execute the JAR from the terminal, but if i execute the JAR by double-clicking it, the file is created in my home directory -.-''
how do i access a file being SURE that that file is in the SAME directory as the JAR file?
(of course also getting the jar absolute path would do the trick since i can get the parent folder from it)

This will give you the full path to the Jar:
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
EDIT: sorry, was in javascript mode when I wrote that :). As was so politely requested, in a static method you should be able to do this:
String path = Me.class.getProtectionDomain().getCodeSource().getLocation().getPath();
(where the class name is Me).

Related

File only accessible when placed in a location where it will be erased from the jar

I'm new to NetBeans IDE, and am struggling with accessing a file after building the jar file. After reading through many posts on this topic, I decided to try the following code:
BufferedReader read = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/file.txt")));
This works fine when my file is placed inside the "build" folder of the project where the .class files are, but of course this is a problem because it is erased in the "clean and build" process when the jar file is created. I have tried placing it in the src folder, in a separate "resources" package, and in the root of directory. I have also tried calling getResourceAsStream() with "file.txt" and "/src/file.txt," but it only works in the above configuration when the file is with the .class files. Any tips would be much appreciated!
Why not have your file folder inside the tomcat bin and refer the directory from your code. So maven clean will not alter the files and you can remove, update file without needing to restart the application. ( here i have file inside etc )
Path: /Users/username/Documents/apache-tomcat-8.5.15/bin/etc
ArrayList<String> readList = null;
String workingDir = System.getProperty("user.dir");
String fileName = "File.txt";
File file = new File(workingDir+"/etc/" + fileName);
readList = resourceReader.readFile(file.getAbsolutePath());
I have method readFile to parse some data and build the ArrayList in the above example.
Read about System Properties
Turns out the solution was really simple...I had been trying to manually create a resources folder, but the contents kept being deleted upon building of the jar. Instead, I created a resources package and put the file into the auto-generated folder inside the src folder, which packaged the file into the jar. Thanks everyone!

File relative to jar using Spring

I work on a Java console application. There is a property in my application.properties file, which contains another file name as a value of a property, like
my.file.location=file:myDir/myFileName
In the code I try to get the file like this:
#Value("${my.file.location}")
private File myfileLocation;
If I start the application from the directory, which contains jar file, the file is resolved, but when I run my application from a different location, the file location is not valid.
I can't have this file on classpath, it must be external to the jar file.
How can I make the file path to be relative to my jar file and not to the current working directory?
I believe this has nothing to do with Spring right? You just want to load configuration file, that is inside your application, unpacked, so the user can modify it, ok?
First, you may try to always setup the working directory, which I believe is more "standard" solution. In windows you can make a link, that specifies the Start in section and contains the path to your jar file (or bat or cmd, whatever).
If you insist on using the jar path, you could use How to get the path of a running JAR file solution. Note, that the jar must be loaded from filesystem:
URI path = MySpringBean.class.getProtectionDomain().getCodeSource().getLocation().toURI();
File myfileLocation = new File(new File(path).getParent(), "/myDir/jdbc.properties");

Simple program throws FileNotFound Exception for relative path

A dumb question, but after a lot of googling, I still can't get it to work.
System.out.print("Start");
File file = new File("TestFile.txt");
Scanner scanner = new Scanner(file);
When I run this, I get a FileNotFound exception. I'm running on NetBeans, and I have placed the TestFile.txt inside the same package as the main class. When I use the absolute path, it works. I can see the see the file next to the .class file inside the build folder. I've tried using the command line, and it doesn't work either.
Relative file paths are not relative to the location of the class file containing the code. They're relative to the directory from which the java executable is started.
Just like, when executing
ls foo
or
dir foo
ls/dir look for the foo directory in the current directory, and not in the directory where the ls executable or dir executable is located.
So, similarly, when executing
java com.foo.bar.MainClass
if the MaiClass file opens the file "foo.txt", it will look for it in the directory where you were when executing the command java com.foo.bar.MainClass.
If you use relative paths the folder that has the file must be in the classpath, so you can put the file in the root folder (if you run the code from a jar file), or add the root folder to your classpath.
If you want to keep the file in that folder you have to include it into the classpath in order to get it work.
Also, the relative path for a java command line program is the root folder, so you can construct the relative path from that point too.
You should put the text file in the 'working directory' of your application. And if you don't want to do that, you should include the folder that contains this file in class path.

How to fix this java.io.FileNotFoundException?

I'm trying to load a .csv file in a program but for some reason, it's unable to find the file. Where should I place the file?
Console
It looks like the file is in the src directory... which almost certainly isn't the working directory you're running in.
Options:
Specify an absolute filename
Copy the file to your working directory
Change the working directory to src
Specify a relative filename, having worked out where the working directory is
Include it as a resource instead, and load it using Class.getResourceAsStream
The file is located in the src directory so in order to access it you should use
src/Elevator.csv
As long as files are located inside your project folder you can access them using relative paths.
For example if a file is located under the Elevator folder then you access the file by using only its filename.
Elevator.csv
A good principle when using additional files in your project is creating separate folders from the ones that the source files are located. So you could create a folder resources under the project folder and place your file there. You can access then the file by using
resources/Elevator.csv
the path which it is trying to read is surely not exact as the path in which that file is actually present.Try printing absolute path of that file and compare it with actual path of your file.
I tried with all the above mention solution, but it didn't work..
but i went to my project folder and delete the target and tried to compile the project again. it then worked successfully

Java JAR: Writing to a file

Currently, in my eclipse project, I have a file that I write to. However, I have exported my project to a JAR file and writing to that directory no longer works. I know I need to treat this file as a classpath resource, but how do I do this with a BufferedWriter?
You shouldn't have to treat it as a classpath resource to write to a file. You would only have to do that if the file was in your JAR file, but you don't want to write to a file contained within your JAR file do you?
You should still be able to create and write to a file but it will probably be relative to the working directory - the directory you execute your JAR file from (unless you use an absolute path). In eclipse, configure the working directory from within the run configuration dialog.
You're probably working in Linux. Because, in Linux, when you start your application from a JAR, the working directory is set to your home folder (/home/yourname/). When you start it from Eclipse, the working directory is set to the project folder.
To make sure you really know the files you are using are located in the project folder, or the folder where your JAR is in, you can use this piece of code to know where the JAR is located, then use the File(File parent, String name) constructor to create your files:
// Find out where the JAR is:
String path = YourClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
path = path.substring(0, path.lastIndexOf('/')+1);
// Create the project-folder-file:
File root = new File(path);
And, from now on, you can create all your File's like this:
File myFile = new File(root, "config.xml");
Of course, root has to be in your scope.
Such resources (when altered) are best stored in a sub-directory of user.home. It is a reproducible path that the user should have write access to. You might use the package name of the main class as a basis for the sub-directory. E.G.
our.com.Main -> ${user.home}/our/com/

Categories