【问题标题】:Referencing java resource files from ColdFusion从 ColdFusion 引用 java 资源文件
【发布时间】:2014-07-22 01:34:20
【问题描述】:

我在我的 CF 代码中使用包含 .properties 文件的 .jar 文件。但是从 CF 运行时似乎找不到 .properties 文件。

我的java代码是:

    String key ="";
    String value ="";

    try {
        File file = new File("src/test.properties");
        FileInputStream fileInput = new FileInputStream(file);
        Properties properties = new Properties();
        properties.load(fileInput);
        fileInput.close();

        Enumeration enuKeys = properties.keys();
        while (enuKeys.hasMoreElements()) {
            key = (String) enuKeys.nextElement();
            value = properties.getProperty(key);
            //System.out.println(key + ": " + value);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        key ="error";
    } catch (IOException e) {
        e.printStackTrace();
        key ="error";
    }

    return(key + ": " + value);

我的 test.properties 文件在项目 src 文件夹中,并确保在编译时选择它。从 Eclipse 运行时,它会给出预期的键和值。但是,当从 CF 运行时,我得到了捕获的错误。

我的 CF 代码很简单:

propTest = CreateObject("java","package.class"); 
testResults = propTest.main2();

是否有一种特殊的方式来引用 .properties 文件以便 CF 可以访问它,还是我需要在 .jar 之外的某个地方包含该文件?

【问题讨论】:

    标签: java eclipse coldfusion properties-file


    【解决方案1】:

    文件("src/test.properties");

    这是因为您使用的是物理文件路径,这意味着它必须存在于 jar 之外的物理磁盘上。此外,它是一个相对文件路径。相对路径取决于您当前的上下文或目录。 CF 中的工作目录与 Eclipse 中的不同。当你在CF中使用jar时,相对路径"src/test.properties"显然解析为一个不存在的文件。因此错误。

    如果你想加载包含在 jar 中的属性文件,你需要使用getResourceAsStream()

    // returns null if path does not exist
    InputStream is = YourClass.class.getResourceAsStream("/test.properties");
    if (is != null) {
       Properties properties = new Properties();
       properties.load(is);
       //... 
    } 
    

    注意:/ 表示包路径的根,也用作路径分隔符

    【讨论】:

      【解决方案2】:

      将来自 ColdFusion 的文件引用作为字符串传递,而不是将文件打包到 jar 中。将 .properties 文件放在 cf/java 应用程序可访问的位置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-21
        • 2010-11-13
        • 2018-06-03
        • 1970-01-01
        • 1970-01-01
        • 2011-03-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多