如何在Java中读取属性文件?

7

我正在使用servlet,其中我硬编码了数据库连接详细信息,因此如果进行任何更改,我必须重新编译代码。因此,我想使用一个.properties文件(稍后可以修改),并将其用作我的数据库连接源。

问题是我不知道如何读取属性文件。请问有人能帮我读取该文件吗?


虽然您已经有很多阅读材料了,但我想向您推荐这篇文章,因为它可能会帮助您基本了解如何组织您的属性。虽然这篇文章相当古老,但自那时以来API并没有发生太大变化。 - crusam
相关链接:https://dev59.com/s07Sa4cB1Zd3GeqP57hx 和 https://dev59.com/Z3I95IYBdhLWcg3wxA8- - BalusC
13个回答

7
   . . .
   // create and load default properties
   Properties defaultProps = new Properties();
   FileInputStream in = new FileInputStream("defaultProperties");
   defaultProps.load(in);
   in.close();

   // create application properties with default
   Properties applicationProps = new Properties(defaultProps);

   // now load properties from last invocation
   in = new FileInputStream("appProperties");
   applicationProps.load(in);
   in.close();
   . . .

这里的示例来自于Properties (Java)

Properties类的方法可能会抛出异常: - 当文件路径无效时(FileNotFoundException)。请尝试创建一个File对象并检查该File是否存在。 - ...


但是我使用了Properties方法,但它抛出了FileNotFound异常。我的代码:Properties prop = new Properties(); prop.load(new FileInputStream("file.properties")); - dean
2
你应该在复制粘贴答案到任何地方之前阅读消息! - Markus Lausberg

5
您可以查看Apache Commons Configuration。 使用它,您可以像这样读取属性文件:
Configuration config = new PropertiesConfiguration("user.properties");
String connectionUrl = config.getString("connection.url");

以下是有关文件位置的信息,这可能也很重要:

如果您没有指定绝对路径,则文件将自动在以下位置中搜索:

  • 当前目录
  • 用户主目录
  • 类路径

因此,在servlet中读取属性文件时,您应该将属性文件放在类路径中(例如,在WEB-INF/classes中)。

您可以在他们的网站上找到更多示例。


3

1
但是我使用了Properties方法,但它抛出了FileNotFound异常。我的代码:Properties prop = new Properties(); prop.load(new FileInputStream("file.properties")); - dean
2
你的属性文件需要在类路径中。 - trutheality

3
在Web应用程序中读取属性文件的最大问题是您实际上不知道文件的实际路径。因此,我们必须使用相对路径,为此,我们必须使用各种函数和类,例如getresourceAsStream(),InputStream,FileinputStream等。
而getReourceAsStream方法在静态和非静态方法中的行为不同.. 您可以按以下方式执行此操作
1. 非静态 InputStream input = getClass()。getClassLoader()。getResourceAsStream(“config.properties”);
2. 静态 InputStream input = ReadPropertyFile.class.getClassLoader()。getResourceAsStream(“config.properties”);
完整参考资料,请参阅以下链接。

http://www.codingeek.com/java/using-getresourceasstream-in-static-method-reading-property-files

http://www.codingeek.com/java/read-and-write-properties-file-in-java-examples/


2
如果您的应用程序很小,只有一两个属性文件中的少数属性,则建议使用JDK自带的Properties类,该类从文件加载属性,并像使用哈希表一样使用它。 Properties类本身继承自Hashtable。但是,如果您的应用程序非常大,具有来自不同来源的大量属性(如属性文件、XML文件、系统属性),则建议使用Apache Commons Configuration。它提供了跨不同配置源的属性的统一视图,并允许您为出现在不同源中的公共属性定义覆盖和优先级机制。请参考这篇文章http://wilddiary.com/reading-property-file-java-using-apache-commons-configuration/,快速了解如何使用Commons Configuration。

2
这可能有效:
Properties prop = new Properties();
FileReader fr = new FileReader(filename);
prop.load(fr);
Set<String> keys = pr.stringPropertyNames();
//now u can get the values from keys.

2
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("my.properties");
Properties p = new Properties();
p.load(in);
in.close();

2
以下代码将添加一个监听器,用于检查是否配置了dbprops系统属性的文件。每隔一定时间,它将检查文件是否已修改,如果已修改,则会从文件中加载属性。 package com.servlets;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class DBPropsWatcherListener
 implements ServletContextListener
{
public void contextInitialized(ServletContextEvent event)
{
ServletContext servletContext = event.getServletContext();
Timer timer = new Timer("ResourceListener");
timer.schedule(new MyWatcherTask(servletContext), 15);
}

public void contextDestroyed(ServletContextEvent event)
{
}

private class MyWatcherTask extends TimerTask
{
private final ServletContext servletContext;
private long lastModifiedTime = -1;


public MyWatcherTask(ServletContext servletContext)
{
    this.servletContext = servletContext;
}

public void run()
{
    try {
        File resourceFile = new File(System.getProperty("dbProps"));
        long current = resourceFile.lastModified();
        if (current > lastModifiedTime) {
            java.io.InputStream dbPropsStream =  new FileInputStream(resourceFile );
            java.util.Properties dbProps = new java.util.Properites();
            dbProps.load(dbPropsStream);
            realoadDBProps();

        }
        lastModifiedTime = current;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

}
}
}

2
下面的程序读取属性文件并使用键值对进行显示。
                File f1 = new File("abcd.properties");
                FileReader fin = new FileReader(f1);
                Properties pr = new Properties();
                pr.load(fin);
                Set<String> keys = pr.stringPropertyNames();
                Iterator<String> it = keys.iterator();
                String key, value;
                while (it.hasNext())
                    {
                        key = it.next();
                        value = pr.getProperty(key);
                        System.out.println(key+":"+value);
                    }

            }

1

Properties类有一个方便的load方法,这是读取Java属性文件最简单的方法。


但是我使用了Properties方法,但它抛出了FileNotFound异常。我的代码:Properties prop = new Properties(); prop.load(new FileInputStream("file.properties")); - dean

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接