[英]How can I read properties file in java class located in a folder outside workspace?
I have a properties file located in C:/codebase/myProject-Authentication/sample.properties
, and my workspace is at C:/codebase/myProject/com.company.team.website/src/.../AccessCodeServlet.java
. 我在
C:/codebase/myProject-Authentication/sample.properties
有一个属性文件,我的工作空间在C:/codebase/myProject/com.company.team.website/src/.../AccessCodeServlet.java
。
So, I need to read sample.properties
from AccessCodeServlet.java
. 因此,我需要从
AccessCodeServlet.java
读取sample.properties
。 AccessCodeServlet
is a servlet. AccessCodeServlet
是一个servlet。
If the properties file is in the same folder as AccessCodeServlet.java
, I can just do this: 如果属性文件与
AccessCodeServlet.java
位于同一文件夹中,则可以执行以下操作:
ResourceBundle bundle = ResourceBundle.getBundle("sample");
But how do I do it when properties file is outside workspace? 但是,当属性文件位于工作空间之外时,该怎么办?
Move the file to a relative path to the workspace before usage? 使用之前将文件移动到工作空间的相对路径吗?
public void MovePropertiesFile()
{
InputStream otherStream = null;
OutputStream workspaceStream = null;
try{
File afile =new File("C:\\somwhere\\.....\\properties.properties");
File bfile =new File("C:\\workspace\\.....\\properties.properties");
otherStream = new FileInputStream(afile);
workspaceStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
while ((length = otherStream .read(buffer)) > 0){
workspaceStream .write(buffer, 0, length);
}
otherStream .close();
workspaceStream .close();
}catch(IOException e){
e.printStackTrace();
}
}
Well, you can add an external folder containing your sample.properties to the classpath in eclipse: 好了,您可以将包含sample.properties的外部文件夹添加到eclipse中的类路径:
Viola - now resource bundles are found! 中提琴-现在找到资源包!
You need to specify absolute path but you shouldn't hard-code it as you correctly surmised. 您需要指定绝对路径,但您不应在正确推测的情况下对其进行硬编码。
You should get the base path of the file(s) from a System property which you can access using System.getProperty("basePath") in your code and which should be prepended to your file name to create an absolute path. 您应该从系统属性中获取文件的基本路径,可以在代码中使用System.getProperty(“ basePath”)访问该系统属性,并且应该在文件名之前添加以创建绝对路径。
While running your application you can specify the path in java command line as follows: 运行应用程序时,可以在java命令行中指定路径,如下所示:
java -DbasePath="/a/b/c" ...
... signifies the current arguments to your Java command to run your program. ...表示运行命令的Java命令的当前参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.