如何读取位于工作区外文件夹中的 java class 中的属性文件?

How can I read properties file in java class located in a folder outside workspace?

我有一个位于 C:/codebase/myProject-Authentication/sample.properties 的属性文件,我的工作区位于 C:/codebase/myProject/com.company.team.website/src/.../AccessCodeServlet.java

所以,我需要从 AccessCodeServlet.javasample.propertiesAccessCodeServlet 是一个 servlet。

如果属性文件与 AccessCodeServlet.java 在同一文件夹中,我可以这样做:

ResourceBundle bundle = ResourceBundle.getBundle("sample");

但是当属性文件在工作区之外时我该怎么办?

使用前将文件移动到工作区的相对路径?

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();
    }
}

好吧,您可以将包含 sample.properties 的外部文件夹添加到 eclipse 中的类路径中:

  • 打开运行配置
  • Select <您的应用条目>
  • 转到 "Classpath" 选项卡
  • Select "User entries"
  • 单击 "Advanced" 按钮
  • 勾选"Add external folder"
  • 单击 "OK" 按钮
  • Select 您的外部文件夹,其中包含 .properties 个文件

Viola - 现在找到资源包了!

您需要指定绝对路径,但不应像您正确推测的那样对其进行硬编码。

您应该从系统 属性 中获取文件的基本路径,您可以在代码中使用 System.getProperty("basePath") 访问该文件,并且应该在前面加上添加到您的文件名以创建绝对路径。

在 运行 运行您的应用程序时,您可以在 java 命令行中指定路径,如下所示:

java -DbasePath="/a/b/c" ...

... 表示您的 Java 命令的当前参数 运行 您的程序。