Reputation: 1736
I've a normal Java class (neither a JSP nor a Servlet) that performs some processing on files like reading, writing, and executing some executable files. How to know the relative path of each file?
I know about getClass().getResourceStream()
, but this is useful only for reading files. And I know about getServletContext().getRealPath()
but my code is in ordinary Java class not a servlet.
I'd like to do the following
String relativePath = "path/to/exe";
Runtime.getRuntime.exec(relativePath);
Upvotes: 0
Views: 3272
Reputation: 7940
Your questions seems to address Java SE and not Java EE. I assume your "exe" file is located relative to your java project? To get the absolute path, you could use:
File f = new File("path/to/exe");
String exePath = f.getAbsolutePath();
Then you could use the absolute path to issue your command. See also: JavaDoc of File.
Upvotes: 0
Reputation: 1109645
And I know about
getServletContext().getRealPath()
but my code is in ordinary Java class not a servlet
Just pass its result to the Java class.
String desiredPath = calculateItSomehowBasedOn(getServletContext().getRealPath("/"));
yourJavaClass.executeExe(desiredPath);
Note that the getRealPath()
will return null
when the deployed WAR is not expanded in local disk file system, but instead in memory. Some production server configurations will do that.
Much better is to make the location of the exe file a configuration file setting. E.g.
path.to.exe = /absolute/path/to/exe
This configuration file can in turn be placed in the classpath, or its path can be added to the classpath. See also Where to place and how to read configuration resource files in servlet based application?
Upvotes: 1