2

Right now I have the absolute file path hardcoded into my Java program so that the Python script can be ran. However, when my program is deployed onto the company's platform, this file path will no longer be correct. The script is located in the same directory of the class which calls it, and this directory structure will not change. Is there a way to run the script just based on it being in the same directory?

4
  • Are you using org.python.util.PythonInterpreter? Commented Jul 8, 2016 at 16:50
  • why do you need absolute path? If it is on the class path, then there should be the way to call it with "./something/script" which would work where ever your app is brought to. Commented Jul 8, 2016 at 17:00
  • @CoderinoJavarino scriptPath.exists() returns false for any relative path and only true for the absolute path. Commented Jul 8, 2016 at 17:05
  • And no I didn't use Jython Commented Jul 8, 2016 at 17:05

2 Answers 2

2

You can use this to return the file path that the Java class was executed from:

final File path = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());

You can then use this path object to load up the current directory and run your Python script.

Sign up to request clarification or add additional context in comments.

Comments

1

After trying what @Confiqure suggested, I found that the path was going one step too far into the directory structure of my program. Instead I tried:

String path = new File("").getAbsolutePath + "/my/path/to/script";

The new File("").getAbsolutePath returned the path to my application and from their I hardcoded the relative path, knowing that the path relative to my own application would never change.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.