user16092902
user16092902

Reputation:

How to get path where my current java file is stored?

I tried most of the answer on Stack Overflow and they give path where my .java file is not present. How to get path where my *.java file is actually present or exist?

Suppose name of my java file is Test.java and it's location is src/main/java/mypackage/Test.java . So I want to print path src/main/java/mypackage.

I deploy my files to some server and then run it there, whever I want to print the path, I get locations like jar:file/ where no files are present.

Upvotes: 1

Views: 1805

Answers (2)

Seth Falco
Seth Falco

Reputation: 640

It's important to note that the location may vary depending on if you're running it in your IDE, or running it from a .jar file.

In development, you can do this using the ClassLoader.

import java.net.URL;

public class Main {

  public static void main(String[] args) {
    ClassLoader loader = Main.class.getClassLoader();
    URL url = loader.getResource("Main.class");
    System.out.println(url);
  }
}

Output when executing from code editor:

file:/tmp/vscodesws_92b4a/jdt_ws/jdt.ls-java-project/bin/Main.class

Output when executing jar file:

jar:file:/home/seth/Downloads/build/Main.jar!/Main.class

I don't think this is a good idea. Especially after you compile your project to a jar, war, or whatever else.


It's important to look at Do Nhu Vy's answer as well. Notice how my solution provides the path to .class files, not .java files.

Upvotes: 2

Vy Do
Vy Do

Reputation: 52666

You cannot get path of current Java file by itself, because Java program executed by Java binary byte code in *.class file(s). Your question is meaningless.

Simple logic, when you put *.class file to another directory, what happen with path result? Specific path will change while *.java file is still in its location.

Upvotes: 3

Related Questions