简体   繁体   English

获取Java EE项目中的相对路径

[英]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. 我有一个普通的Java类(JSP和Servlet都没有),该类对文件执行一些处理,例如读取,写入和执行一些可执行文件。 How to know the relative path of each file? 如何知道每个文件的相对路径?

I know about getClass().getResourceStream() , but this is useful only for reading files. 我知道getClass().getResourceStream() ,但这仅对读取文件有用。 And I know about getServletContext().getRealPath() but my code is in ordinary Java class not a servlet. 而且我知道getServletContext().getRealPath()但是我的代码在普通Java类中而不是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 而且我知道getServletContext().getRealPath()但是我的代码在普通的Java类中而不是servlet中

Just pass its result to the Java class. 只需将其结果传递给Java类即可。

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. 请注意,当部署的WAR不在本地磁盘文件系统中而是在内存中扩展时, getRealPath()将返回null Some production server configurations will do that. 某些生产服务器配置将执行此操作。

Much better is to make the location of the exe file a configuration file setting. 更好的方法是将exe文件的位置设置为配置文件设置。 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? 另请参见在基于Servlet的应用程序中的何处放置以及如何读取配置资源文件?

Your questions seems to address Java SE and not Java EE. 您的问题似乎是针对Java SE而非Java EE的。 I assume your "exe" file is located relative to your java project? 我假设您的“ exe”文件相对于您的Java项目位于? 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 . 另请参阅: File的JavaDoc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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