0

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);
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
Islam Hassan
  • 1,684
  • 4
  • 24
  • 40

2 Answers2

1

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?

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
0

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.

Arjan Tijms
  • 36,666
  • 12
  • 105
  • 134
Behe
  • 6,543
  • 3
  • 29
  • 39
  • No the problem is related to J2EE. This code works well in J2SE, but writing this in a J2EE application produces errors as the root directory of my J2EE is my home directory, while the root directory of a J2SE application is the project's itself. – Islam Hassan Jul 01 '12 at 00:11
  • That was unclear for me. "Ordinary Java class" and "Normal Java class" did not sound like a J2EE application. How about adding the "errors" to the question? What are you doing? What type of J2EE application do you have? – Behe Jul 01 '12 at 00:19