java.util.ResourceBundle

Java中提供了一个工具类 ResourceBundle

可以直接读取src下的properties文件(注意只能读该文件)


再通过getString("");通过键获取值:

例如:

ResourceBundle rb = ResourceBundle.getBundle("log4j");
String str = rb.getString("log4j.rootLogger");
System.out.println(str);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很遗憾,java.util.ResourceBundle 并不支持直接处理 JSON 格式的数据,它主要用于处理属性文件(即 .properties 文件)。如果需要处理 JSON 数据,可以考虑使用其他第三方库,比如 Jackson、Gson 等。 以 Jackson 为例,以下是一个处理 JSON 数据的示例: ```java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonResourceBundle { private final ObjectMapper mapper = new ObjectMapper(); public ResourceBundle getBundle(String baseName) { return new JsonResourceBundleImpl(baseName); } private class JsonResourceBundleImpl extends ResourceBundle { private final JsonNode node; public JsonResourceBundleImpl(String baseName) { try { String jsonStr = // 从文件或其他来源中读取 JSON 字符串 node = mapper.readTree(jsonStr); } catch (IOException e) { throw new IllegalArgumentException("Invalid JSON format", e); } } @Override protected Object handleGetObject(String key) { JsonNode valueNode = node.get(key); if (valueNode == null) { return null; } if (valueNode.isValueNode()) { return valueNode.asText(); } // 如果需要支持多层嵌套,可以递归处理 throw new IllegalArgumentException("Invalid JSON format"); } @Override public Enumeration<String> getKeys() { return node.fieldNames(); } } } ``` 使用示例: ```java ResourceBundle bundle = new JsonResourceBundle().getBundle("messages.json"); String greeting = bundle.getString("greeting"); System.out.println(greeting); // 输出:Hello, world! ``` 其中 `messages.json` 文件内容如下: ```json { "greeting": "Hello, world!", "farewell": "Goodbye!" } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值