方便操作Properties的Java類庫:props4j

jopen 8年前發布 | 10K 次閱讀 props4j Java開發

方便操作Properties的Java類庫。簡單和實用的properties工具,沒有任何依賴。

Cases

Props with auto convert values

import base.props4j.impl.MapProps;

MapProps props = new MapProps();
props.putVal("key1", 1);
props.putVal("key2", "val2");
props.putVal("key3", true);

String strVal_1 = props.strVal("key1"); //"1"
long longVal_1 = props.longVal("key1"); //1L
Boolean boolVal_1 = props.boolVal("key1"); //false

Default values for empty keys or bad values

int defVal = props.intVal("unknown-key", 42); //42

File props with updates check

import base.props4j.impl.FileProps;
import java.io.File;

File file = new File("test.properties");
writeToFile(file, "key1 = 1");

FileProps props = new FileProps(file);
int val = props.intVal("key1"); //1

//update file
writeToFile(file, "key1 = 2");

Thread.sleep(...);

int newVal = props.intVal("key1"); //2

MultiProps for many sources

import base.props4j.impl.FileProps;
import base.props4j.impl.MultiProps;

MultiProps props = new MultiProps();
props.addSource(new FileProps(file1));
props.addSource(new FileProps(file2));

Enum for keys!

import base.props4j.DefValKey;

public enum Keys implements DefValKey {

    planets_in_solar_system(8),
    is_frog_green(true),
    myName("Evgeny"),
    star_wars_episodes_count(999.999d),
    ...
}


MapProps props = new MapProps();
int defVal = Keys.planets_in_solar_system.intFrom(props); //8

props.putVal(planets_in_solar_system, 9);
int updatedVal = Keys.planets_in_solar_system.intFrom(props); //9

Expressions ${...} in values

props.putVal("url", "127.0.0.1");
props.putVal("link1", "${url}/some1");
props.putVal("link2", "${url}/some2");

String link1 = props.strVal("link1"); // 127.0.0.1/some1
String link2 = props.strVal("link2"); // 127.0.0.1/some2

Code examples

Production ready

Props4j has been successfully used on Cheapchat.me and in open source live-chat-engine project.

Installation to your project

Java 8 is required (sources can easily be ported to Java 6 or 7 -- but I'm on Java 8 now :))

by Maven

via stackoverflow

<dependencies>
    <dependency>
        <groupId>com.github.edolganov</groupId>
        <artifactId>props4j</artifactId>
        <version>1.0</version>
    </dependency>
</dependencies>

<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

項目主頁:http://www.baiduhome.net/lib/view/home/1451046744651

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!