简体   繁体   English

具有“user.dir”系统属性的相对文件路径

[英]Relative file path with “user.dir” system property

I'm trying to read in a local file in my web application on the server. 我正在尝试在服务器上的Web应用程序中读取本地文件。 When testing this outside of the deployment to JBoss, the file path is correct. 在部署之外对JBoss进行测试时,文件路径是正确的。 However, when I deploy it to JBoss the file path changes JBoss's bin directory. 但是,当我将它部署到JBoss时,文件路径会改变JBoss的bin目录。 The user.dir system property changes when it's deployed as a war. user.dir系统属性在部署为战争时会更改。

How do I prevent that without using an absolute file path? 如何在不使用绝对文件路径的情况下防止这种情况?

I want to avoid an absolute file path, because the project needs to be replicated on multiple machines that have different directory structures. 我想避免使用绝对文件路径,因为需要在具有不同目录结构的多台计算机上复制项目。

String curDir = System.getProperty("user.dir");

String fileLocation = curDir.toString() + "/end/of/path/to/flat.json";
JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(fileLocation)));

Have you tried to call from the 你试过打电话吗?

HttpServeltRequest.getServletContext().getRealPath("META-INT/aop.xml");

It give you the real path on the current operating system. 它为您提供了当前操作系统的真实路径。

Regards, 问候,

FT FT

Thanks to this question and answer I have found a solution. 感谢这个问题和答案,我找到了解决方案。 I'm not sure if this is the best way of doing it, but it works. 我不确定这是否是最佳方式,但它确实有效。 I added src/main/resources folder in my web app, and put the files I need to access there. 我在我的网络应用程序中添加了src/main/resources文件夹,并将我需要访问的文件放在那里。

Resources from src/main/resources will be put onto the root of the classpath, so you'll need to get the resource as: 来自src / main / resources的资源将被放到类路径的根目录中,因此您需要获取资源:

The code: 编码:

String file = "/flat.json";

JsonReader reader = new JsonReader(new InputStreamReader(getClass().getResourceAsStream(file)));

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

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