简体   繁体   English

如何在java文件中给我的文件相对路径?

[英]How to give relative path for my file in java file?

I am using tomcat server for my java application(Servlet,jsp).In my servlet page calling one java class function.Actually the java file is written separately and i will call the function written inside it.With in the function, i have to read one config(user defined) file for some purpose.so, i am using File class for that. 我正在使用tomcat服务器为我的java应用程序(Servlet,jsp)。在我的servlet页面中调用一个java类函数。实际上java文件是单独编写的,我将调用它内部编写的函数。在函数中,我必须为某种目的读取一个配置(用户定义)文件。因此,我正在使用File类。

But, here i have to give relative path of the config file(user defined).Because, now i am running this application in local windows server.But my live server is based on Linux.So, the file path is changed in linux. 但是,这里我必须给出配置文件的相对路径(用户定义)。因为,现在我在本地Windows服务器上运行这个应用程序。但我的实时服务器基于Linux。因此,文件路径在linux中更改。

File f1=new File("D:\tomcat\webapp\myapp\WEB-INF\src\point_config.txt");  -- windows
File f1=new File("D:\ravi\tomcat\webapp\myapp\WEB-INF\src\point_config.txt");  -- linux

So, i have to give relative path of the file that is common to both windows and linux machine. 因此,我必须给出Windows和Linux机器都通用的文件的相对路径。

Is there a way to do this? 有没有办法做到这一点?

Please guide me to get out of this issue? 请指导我摆脱这个问题?

Place your config file under your webapp WEB-INF/classes folder and read like this in code 将您的配置文件放在您的webapp WEB-INF / classes文件夹下,并在代码中如下所示

InputStream is= 
   YourClassName.class.getResourceAsStream("point_config.txt");

The path of the config file leads into the WEB-INF folder 配置文件的路径进入WEB-INF文件夹

tomcat\webapp\myapp\WEB-INF\src\point_config.txt

Anything inside WEB-INF is protected and cannot be user-defined once the web application has launched. Web应用程序启动后,WEB-INF内的所有内容都将受到保护,并且不能由用户定义。 If you meant to read from a user-defined configuration file from the file system, please use an API like the common configuration API . 如果您打算从文件系统中读取用户定义的配置文件,请使用通用配置API之类的API

If you want to insist on keeping the file inside the WEB-INF folder, use the Class.getResourceAsStream() method to obtain the configuration instead. 如果要坚持将文件保留在WEB-INF文件夹中,请使用Class.getResourceAsStream()方法来获取配置。 That would not make the configuration user-defined though. 但这不会使配置由用户定义。

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

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