深圳同城快跑筆試題目 2 實現json字符串保存到本地硬盤

 

    //從給定位置讀取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();
    }
    //給定路徑與Json文件,存儲到硬盤
    public static void writeJson(String path,Object json,String fileName){
        BufferedWriter writer = null;
        File file = new File(path + fileName + ".json");
        //若是文件不存在,則新建一個
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //寫入
        try {
            writer = new BufferedWriter(new FileWriter(file));
            writer.write(json.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(writer != null){
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        System.out.println("文件寫入成功!");
    }
}
相關文章
相關標籤/搜索