简体   繁体   中英

Get relative path in Java EE project

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);

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. Eg

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM