属性文件中的 Java 连接

标签 java properties concatenation

我创建了一个名为 myproperties.properties 的属性文件,如下所示:

test.value1=one
test.value2=two

我读取该文件的java代码如下:

String test = Utility.getInstance().getProperty("test.value1");

其中类 Utility 是这样定义的:

public class Utility {

    private static Utility _instance = null;
    private static Properties properties = new Properties();

    static public Utility getInstance(){
        if (_instance == null) {
            _instance = new Utility();
        }
        return _instance;
    }

    private Utility(){
        loadUtility();
    }

    public String getProperty(String tgtPropertyName) {
        Object prop = properties.get(tgtPropertyName);

        if (prop != null) {
            return prop.toString();
        } else {
            return null;
        }
    }

    private void loadUtility(){
        String filename = null;
        try{
            filename = getClass().getClassLoader().getResource("myproperties").getFile();
            InputStream file = new FileInputStream(new File(filename));
            properties.load(file);
            Iterator iter = properties.keySet().iterator();
            while (iter.hasNext()){
                System.out.println("FILE LOADED");
            }
        }catch(Exception e){
        }    
    }

}

这段代码工作正常。现在我必须在我的属性文件中添加一个串联:

test.value3=${test.value1}${test.value2}

这不起作用,因为我的 Java 代码无法解释 ${}。

异常(exception)情况是:

由以下原因引起:java.lang.IllegalStateException:流处理程序不可用,原因是:对于输入字符串:“${test.value1}”

为什么?

最佳答案

使用下面的代码连接属性文件中的 type.value3

Properties prop=null;
public FileReader FileLoader() throws FileNotFoundException
{
    File file=new File("myproperties.properties");
    FileReader fileReader=new FileReader(file);
    return fileReader;

}
public String propertyLoader(String key) throws IOException
{
    FileReader fileReader=FileLoader();
    prop=new Properties();
    prop.load(fileReader);
    String value=prop.getProperty(key);

    return value;

}
public void resultWriter() throws IOException
{
    String value1=propertyLoader("test.value1");
    String value2=propertyLoader("test.value2");
    String res=value1+value2;
    System.out.println(res);
    FileWriter fw=new FileWriter("myproperties.properties");
    prop=new Properties();
    prop.setProperty("test.value3", res);
    prop.store(fw, null);


}
public static void main(String[] args) throws IOException 
{
    UtilityNew util=new UtilityNew();
    util.resultWriter();
    System.out.println("Success");

}

关于属性文件中的 Java 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49108954/

相关文章:

java - 在 45 天(左右)内从 PHP/Ajax 切换到 Java

JAVA+扫描文档

Objective-c 在 init 方法中使用父属性

vb.net - 通过属性分配给结构变量

java - 如何正确构建应用程序结构来使用资源?

c# - 如何将数组内容与其索引值连接起来

java - Opencv4Android 不满意的链接器错误时刻

java - 如何使字符串与 Reader 或 InputStream 类型兼容?

linux - 使用linux合并同一文件中的列

python - Django Queryset 用于连续查询 first_name 和 last_name 的全名