java 怎么读取test.json 文件,怎么改这个错误

图片描述

package com.utils;
import java.io.*;

public class JsonUtils {
    public static String start(String pathString) {
        System.out.println(pathString);
        return pathString;
    }
    //从给定位置读取Json文件
    public static String readJson(String path){
        //从给定位置获取文件
        File file = new File(path);
        BufferedReader reader = null;
        //返回值,使用StringBuffer
        StringBuffer data = new StringBuffer();
        //
        try {
            reader = new BufferedReader(new FileReader(file));
            //每次读取文件的缓存
            String temp = null;
            while((temp = reader.readLine()) != null){
                data.append(temp);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭文件流
            if (reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return data.toString();
    }
}
package com.utils;


public class utilsTest {

    public static void main(String[] args) {
        String jo = JsonUtils.readJson("./test.json");
        System.out.println(jo);
    }

}
{
  "cat":"it",
  "languages":[
    {"id":1,"ide":"Eclipse","name":"Java"},
    {"id":2,"ide":"Xcode","name":"Swift"},
    {"id":3,"ide":"Visual Studio","name":"C#"}
  ],
  "pop":true
}
阅读 3k
1 个回答
String classPath = JsonUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();

JsonUtils.readJson(classPath + "test.json");

编译完成后,class 文件和 json 文件在 target 目录下,你可以观察一下这个目录

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题