我有一个配置值的键/值对列表,我想将其存储为Java属性文件,然后进行加载和遍历。

问题:

我是否需要将文件存储在与装入它们的类相同的包中,或者它应该放置在任何特定的位置? 文件是否需要以任何特定的扩展名结束,或者。txt OK? 如何在代码中加载文件 我如何遍历里面的值?


当前回答

例子:

Properties pro = new Properties();
FileInputStream in = new FileInputStream("D:/prop/prop.properties");
pro.load(in);
String temp1[];
String temp2[];
// getting values from property file
String username = pro.getProperty("usernamev3");//key value in prop file 
String password = pro.getProperty("passwordv3");//eg. username="zub"
String delimiter = ",";                         //password="abc"
temp1=username.split(delimiter);
temp2=password.split(delimiter);

其他回答

属性已经成为遗产。首选项类优先于属性。

偏好数据的层次集合中的一个节点。这个类允许应用程序存储和检索用户和系统首选项以及配置数据。此数据持久地存储在依赖于实现的后备存储区中。典型的实现包括平面文件、特定于操作系统的注册表、目录服务器和SQL数据库。该类的用户不需要关心后台存储的细节。

与基于字符串的键值对的属性不同,Preferences类有几个方法用于在Preferences数据存储中获取和放置基本数据。我们只能使用以下类型的数据:

字符串 布尔 双 浮动 int 长 字节数组

要加载属性文件,可以提供绝对路径,如果属性文件在类路径中,则使用getResourceAsStream()。

package com.mypack.test;

import java.io.*;
import java.util.*;
import java.util.prefs.Preferences;

public class PreferencesExample {

    public static void main(String args[]) throws FileNotFoundException {
        Preferences ps = Preferences.userNodeForPackage(PreferencesExample.class);
        // Load file object
        File fileObj = new File("d:\\data.xml");
        try {
            FileInputStream fis = new FileInputStream(fileObj);
            ps.importPreferences(fis);
            System.out.println("Prefereces:"+ps);
            System.out.println("Get property1:"+ps.getInt("property1",10));

        } catch (Exception err) {
            err.printStackTrace();
        }
    }
}

xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE preferences SYSTEM 'http://java.sun.com/dtd/preferences.dtd'>
<preferences EXTERNAL_XML_VERSION="1.0">
<root type="user">
<map />
<node name="com">
  <map />
  <node name="mypack">
    <map />
    <node name="test">
      <map>
        <entry key="property1" value="80" />
        <entry key="property2" value="Red" />
      </map>
    </node>
  </node>
</node>
</root>
</preferences>

看看这篇关于偏好商店内部的文章

1)在类路径中有你的属性文件是很好的,但你可以把它放在项目的任何地方。

下面是如何从类路径加载属性文件并读取所有属性。

Properties prop = new Properties();
InputStream input = null;

try {

    String filename = "path to property file";
    input = getClass().getClassLoader().getResourceAsStream(filename);
    if (input == null) {
        System.out.println("Sorry, unable to find " + filename);
        return;
    }

    prop.load(input);

    Enumeration<?> e = prop.propertyNames();
    while (e.hasMoreElements()) {
        String key = (String) e.nextElement();
        String value = prop.getProperty(key);
        System.out.println("Key : " + key + ", Value : " + value);
    }

} catch (IOException ex) {
    ex.printStackTrace();
} finally {
    if (input != null) {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2)属性文件的扩展名为.properties

默认情况下,Java在应用程序的工作目录中打开它(这种行为实际上取决于所使用的操作系统)。要加载一个文件,请执行:

Properties props = new java.util.Properties();
FileInputStream fis new FileInputStream("myfile.txt");
props.load(fis)

因此,任何文件扩展名都可以用于属性文件。此外,文件也可以存储在任何地方,只要您可以使用FileInputStream。

需要注意的是,如果使用现代框架,该框架可能提供打开属性文件的其他方法。例如,Spring提供了一个ClassPathResource来从JAR文件中使用包名加载属性文件。

至于遍历属性,一旦加载了属性,它们就存储在java.util.Properties对象中,该对象提供了propertyNames()方法。

在Java 8中获取所有属性

public static Map<String, String> readPropertiesFile(String location) throws Exception {

    Map<String, String> properties = new HashMap<>();

    Properties props = new Properties();
    props.load(new FileInputStream(new File(location)));

    props.forEach((key, value) -> {
        properties.put(key.toString(), value.toString());
    });

    return properties;
}

例子:

Properties pro = new Properties();
FileInputStream in = new FileInputStream("D:/prop/prop.properties");
pro.load(in);
String temp1[];
String temp2[];
// getting values from property file
String username = pro.getProperty("usernamev3");//key value in prop file 
String password = pro.getProperty("passwordv3");//eg. username="zub"
String delimiter = ",";                         //password="abc"
temp1=username.split(delimiter);
temp2=password.split(delimiter);