gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:18:40 27 4
gpt4 key购买 nike

我有一个普通的 Java 类(既不是 JSP 也不是 Servlet),它对文件执行一些处理,例如读取、写入和执行一些可执行文件。如何知道每个文件的相对路径?

我知道getClass().getResourceStream(),但这仅对读取文件有用。我知道 getServletContext().getRealPath() 但我的代码是普通的 Java 类而不是 servlet。

我想做以下事情

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

只需将其结果传递给 Java 类即可。

String desiredPath = calculateItSomehowBasedOn(getServletContext().getRealPath("/"));
yourJavaClass.executeExe(desiredPath);

请注意,当部署的 WAR 不是在本地磁盘文件系统中扩展而是在内存中扩展时,getRealPath() 将返回 null。一些生产服务器配置可以做到这一点。

更好的方法是将 exe 文件的位置设置为配置文件设置。例如

path.to.exe = /absolute/path/to/exe

这个配置文件可以依次放置在类路径中,也可以将其路径添加到类路径中。另请参阅Where to place and how to read configuration resource files in servlet based application?

关于java - 获取Java EE项目中的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11278474/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com