Chris
Chris

Reputation: 618

Reading file right outside jar

So I have a .jar file in a folder and I have some input files in that folder. However, the program looks for the file in the home folder (several layers up). I want it obviously to read it from the folder that it's in but I don't want to be explicit about the file path to my folder because other people won't necessarily put their .jar file in the same spot.

Is there a way to read a file directly outside of the jar file? If not, is there a way to do this without hard-coding the file path?

edit:

here's the code. It just checks if the input files exist.

package main;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * Created by chris on 12/1/15.
 * Control class that will be run when the jar is run.
 */
public class run {
    public static void main(String[] args) throws Exception {
        if (!(new File("settings.txt").exists())) {
            start.run();
        }
        if (!(new File("api_key.txt").exists())) {
            alert.display("Make your api_key.txt please.");
        } else {
            gatherData.run();
        }
    }
}

edit 2: I've tried adding relative references with "./" at the beginning but that doesn't work either.

Upvotes: 1

Views: 4548

Answers (4)

Java Doe
Java Doe

Reputation: 346

If you can rely on your .jar file being on the file system, you can get the absolute path of it by

new File(run.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());

which can result in a SecurityException if a SecurityManager is present and not allowing this.

Another possibility would be to use

(new File(System.getProperty("java.class.path"))).getAbsolutePath();

The folder of the jar file can then be obtained using getParentFile()

Upvotes: 3

The JAR files not neccesarly load from file system, and when loaded from file system can be any directory where the application start from - so relative path is not a good idea. The JAR files can from other types of source not only FileSystem, because it can be stream. I think the best way if there is a system parameter where you can pass the directory or working directory when you start the JAR file.

Upvotes: 0

Vamshi Krishna Alladi
Vamshi Krishna Alladi

Reputation: 438

If I am not wrong you are trying to access a file right in the same folder as that of the .jar file.

This can easily be done using the relative URL. By relative URL, I meant using new File("./settings.txt"), this searches for the file in the folder same as that of the running .jar file. however you can use "../settings.txt" to look for the file one folder up.

"./" refers same directory "../" refers one directory up.

Upvotes: 1

Ashish Nijai
Ashish Nijai

Reputation: 321

Just use ./ before file names.

Upvotes: 0

Related Questions