json数据存入本地文件以及数据读取

时间:2025-04-28 07:14:13

直接复制,带数据测试

public class JsonUtils {

    //从给定位置读取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 = ()) != null){
                (temp);
                (data);
            }
        } catch (FileNotFoundException e) {
            ();
        } catch (IOException e) {
            ();
        }finally {
            //关闭文件流
            if (reader != null){
                try {
                    ();
                } catch (IOException e) {
                    ();
                }
            }
        }
        return ();
    }

    //给定路径与Json文件,存储到硬盘
    public static void writeJson(String path,Object json,String fileName){
        BufferedWriter writer = null;
        File file = new File(path + fileName);
        //如果文件不存在,则新建一个
        if(!()){
            try {
                ();
            } catch (IOException e) {
                ();
            }
        }
        //写入
        try {
            writer = new BufferedWriter(new FileWriter(file));
            (());
        } catch (IOException e) {
            ();
        }finally {
            try {
                if(writer != null){
                    ();
                }
            } catch (IOException e) {
                ();
            }
        }
//        ("文件写入成功!");
    }

    public static void main(String[] args) {
        Map<String,Object> map = new HashMap<String,Object>();
        ("name","ggrk");
        ("password","123456");
        JSONObject jsonObject = (map);
        ("D://",jsonObject,"");
        ("D://");
    }