【问题标题】:How to read from a properties file in Eclipse Java Dynamic Web Project?如何从 Eclipse Java 动态 Web 项目中的属性文件中读取?
【发布时间】:2014-02-06 02:17:42
【问题描述】:

我想我确实想做他所做的事情here

但对我来说有点不同。我首先检查文件是否存在:

File f = new File("properties.txt");
System.out.println(f.exists());

我没有其他帖子中描述的文件夹/project/WebContent/WEB-INF/classes,但我编译的类在/project/build/classes,所以我把我的属性文件放在那里(确切地说:在我正在访问的类的包文件夹中文件)。

但它仍然打印false。也许我做错了,如果是,请告诉我。

【问题讨论】:

标签: java eclipse file


【解决方案1】:

如果您的文件位于类路径或类文件夹中,则不仅仅是从类路径获取路径。不要使用java.io.File 的相对路径,它取决于您在JAVA 代码中无法控制的当前工作目录。

你可以这样试试:

URL url = getClass().getClassLoader().getResource("properties.txt");
File f = new File(url.getPath());
System.out.println(f.exists());  

如果您的文件properties.txt 位于任何在getResource(...) 函数中提供相对路径的包中。例如getResource("properties\\properties.txt")

【讨论】:

  • 我将文件放在/project/build/classes 下,我尝试了您的建议。我在这行File f = new File(url.getPath()); 中得到一个NullPointerException。之后,我尝试了System.out.println(url.getPath()); 并且也得到了异常,因此该类似乎无法访问该文件。是不是放错地方了?还是我必须像类路径一样更改?
  • 'getResouce(...)' 参数中给出的路径是什么?确保文件位于您提供的路径上。
  • System.out.println(f.getAbsolutePath());
【解决方案2】:

执行此操作的代码非常简单。假设您有一个名为 SampleApp.war 的 war 文件,它的根目录下有一个名为 myApp.properties 的属性文件:

SampleApp.war

|

   |-------- myApp.properties

   |

   |-------- WEB-INF

                |
                |---- classes
                         |
                         |----- org
                                 |------ myApp
                                           |------- MyPropertiesReader.class

假设您要读取属性文件中名为abc 的属性:

myApp.properties:

abc = someValue;
xyz = someOtherValue;

假设您的应用程序中的类org.myApp.MyPropertiesReader 想要读取该属性。这是相同的代码:

package org.myapp;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Simple class meant to read a properties file
 * 
 * @author Sudarsan Padhy
 * 
 */
public class MyPropertiesReader {

    /**
     * Default Constructor
     * 
     */
    public MyPropertiesReader() {

    }

    /**
     * Some Method
     * 
     * @throws IOException
     * 
     */
    public void doSomeOperation() throws IOException {
        // Get the inputStream
        InputStream inputStream = this.getClass().getClassLoader()
                .getResourceAsStream("myApp.properties");

        Properties properties = new Properties();

        System.out.println("InputStream is: " + inputStream);

        // load the inputStream using the Properties
        properties.load(inputStream);
        // get the value of the property
        String propValue = properties.getProperty("abc");

        System.out.println("Property value is: " + propValue);
    }

}

【讨论】:

    猜你喜欢
    • 2015-11-19
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 2019-10-10
    相关资源
    最近更新 更多