有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在EclipseJava动态Web项目中读取属性文件?

我想我确实想做他做的here

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

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

我没有另一篇文章中描述的/project/WebContent/WEB-INF/classes文件夹,但我编译的类在/project/build/classes中,所以我把属性文件放在那里(确切地说:在我访问该文件的类的包文件夹中)

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


共 (1) 个答案

  1. # 1 楼答案

    实现这一点的代码非常简单。让我们假设您有一个名为^ {CD1>}的WAR文件,它的根目录下有一个名为^ {CD2>}的属性文件:

    SampleApp.war
    
    |
    
       |     myApp.properties
    
       |
    
       |     WEB-INF
    
                    |
                    |   classes
                             |
                             |  - org
                                     |    myApp
                                               |   - MyPropertiesReader.class
    

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

    myApp.properties中:

    abc = someValue;
    xyz = someOtherValue;
    

    让我们考虑在您的应用程序中存在的类^ {CD5>}想读取属性。下面是同样的代码:

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