zoukankan      html  css  js  c++  java
  • java保存json格式数据,保存字符串和读取字符串

    1、java保存json格式数据,保存字符串和读取字符串

    import java.io.*;
    
    class RWJson {
        public void wiite(String s, String toString) {
            BufferedWriter writer = null;
            File file = new File(s);
            //如果文件不存在,则新建一个
            if(!file.exists()){
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //写入
            try {
                writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,false), "UTF-8"));
                writer.write(toString);
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(writer != null){
                        writer.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("文件写入成功!");
        }
    
        public String readJson(String fileName) {
    
            BufferedReader reader = null;
            StringBuilder laststr = new StringBuilder();
            try {
                FileInputStream fileInputStream = new FileInputStream(fileName);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
                reader = new BufferedReader(inputStreamReader);
                String tempString = null;
                while ((tempString = reader.readLine()) != null) {
                    laststr.append(tempString);
                }
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return laststr.toString();
        }
    
    }
  • 相关阅读:
    96. Unique Binary Search Trees1和2
    576. Out of Boundary Paths
    686. Repeated String Match判断字符串重复几次可以包含另外一个
    650. 2 Keys Keyboard
    Penetration Test
    Penetration Test
    Penetration Test
    Penetration Test
    CISSP 考试经验分享
    2019-2020 ICPC Asia Hong Kong Regional Contest J—Junior Mathematician 数位dp
  • 原文地址:https://www.cnblogs.com/wuzaipei/p/10755115.html
Copyright © 2011-2022 走看看