Damotorie
Damotorie

Reputation: 596

How can I get path java source code in runtime?

Is there no way to get path of Java source code in runtime?

Python can get it's path in runtime by using below code

import os
file_path = (os.path.dirname(os.path.realpath(__file__)) )

Many people saids I can get path by using System.getProperty("user.dir") or new File(".").getAbsolutePath().
But both method returns the path where java source code is executed...

For example, if source code is in /User/Desktop/Project/src/test.java and execute it at /User/Desktop, it returns /User/Desktop instead of /User/Desktop/Project/src/test.java.

Is there no way to get path of source file?
⋇This java file works as servlet to handle AJAX request


Addition - Purpose of finding source code path

I wrote python script and executing it by using Runtime().getRuntime().exec().
I want to find python script without absolute path (I don't like path hardcoding).
So I'm trying to find java source code path and compute python source code path based on java path.

Upvotes: 2

Views: 1337

Answers (2)

talex
talex

Reputation: 20446

You can't do this in java, because (unlike Python) java is compiled language and source code usually not bundled in application.

Upvotes: 3

River
River

Reputation: 9

Maybe we can use the script "echo $PATH", it will print the whole Path that include the "JAVA_HOME" if you are run on Linux. The batch script for Windows is "where java", it will return the java's path. Hopes it can help you.

Upvotes: -2

Related Questions