用值初始化 Properties 对象的最短方法是什么,以替换下面的代码?
Properties properties = new Properties();
properties.put("key1", "value1");
properties.put("key2", "value2");
properties.put("key3", "value3");
我在创建单元测试时遇到了这个问题,因此代码不需要处理很多条目,3-5 个就足够了。对于许多用例来说,从文件加载是一个很好的解决方案,但需要一些易于使用且只需最少努力的解决方案。
最佳答案
虽然我认为您问题中的properties.put方法需要最少的努力,但如果这看起来更容易,您可以使用以下方法(我们将它用于从某些文件粘贴键=值对的情况,intellij添加粘贴多行时的\n)
Properties properties = new Properties();
properties.load(new ByteArrayInputStream("key1=value1\nkey2=value2\nkey3=value3".getBytes(StandardCharsets.ISO_8859_1)));
编辑使用字符集ISO_8859,感谢dnault指出
关于java - 使用值初始化 Properties 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37691277/