java读取json文件的2种方式例子
1 背景介绍
研发过程中,经常会涉及到读取配置文件等重复步骤,也行是.conf文件,也许是.json文件,但不管如何他们最终都需要进入到jave的inputStream里面。下面以读取.json文件为例
2 FileInputStream读取
需要1个参数:
- fileName: 文件名,一般为绝对路径,不然可能会找不到。或者和java文件同一个路径下
static String readWithFileInputStream(){
String jsonString;
//System.getProperty("user.dir")为获取根目录
//File.separator为不同操作系统的分隔符,linux和win是不一样的
//tempFilePath该字符串里面为我们配置文件的路径
String fileName = "xx_config.json";
// String tempFilePath = System.getProperty("user.dir") + File.separator + "resource" + File.separator + fileName;
// System.out.print(tempFilePath);
StringBuilder sb = new StringBuilder();
try{
InputStream input = new FileInputStream(fileName);
byte[] buffer = new byte[1024];
int length = 0;
length = input.read(buffer);
while(length != -1){
sb.append(new String(buffer, 0 , length));
length = input.read(buffer);
}
}catch (Exception e){
e.printStackTrace();
}
return jsonString = sb.toString();
}最终返回一个String。然后通过JSON工具就可以转为自己想读取到模型啦。
TargetConfig config = (TargetConfig) JSON.parseObject(jsonString, TargetConfig.class);
但该种方式不灵活,需要把路径写死,或者写成绝对路径。
3 ClassLoader读取
需要2个参数:
- fileName: 文件名
- ClassLoader: 类加载器,一般为当前类
static String readWithClassLoader() throws IOException {
String fileName = "xx_config.json";
ClassLoader classLoader = TargetConfig.class.getClassLoader();
BufferedReader reader = null;
InputStream inputStream = classLoader.getResourceAsStream(fileName);
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder content = new StringBuilder();
String line = reader.readLine();
while (!StringUtil.isEmpty(line)) {
content.append(line);
line = reader.readLine();
}
return content.toString();
}和之前一样,最终返回一个String。然后通过JSON工具就可以转为自己想读取到模型啦。
TargetConfig config = (TargetConfig) JSON.parseObject(jsonString, TargetConfig.class);
但使用类加载读取,可以不用写死路径。比第一种要灵活很多。

总结
到此这篇关于java读取json文件的2种方式的文章就介绍到这了,更多相关java读取json文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Mybatis-Plus中updateById方法不能更新空值问题解决
本文主要介绍了Mybatis-Plus中updateById方法不能更新空值问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2022-08-08
Spring中@Import的各种用法以及ImportAware接口详解
这篇文章主要介绍了Spring中@Import的各种用法以及ImportAware接口详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-10-10
解决idea中maven项目打包成jar报错:没有主清单属性的问题
这篇文章主要给大家分享了idea中maven项目打包成jar,报错没有主清单属性解决方法,文中有详细的解决方法,如果又遇到同样问题的朋友可以参考一下本文2023-09-09


最新评论