java 《十五》io读取jsonObject和jsonArray文件返回json

package com.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 读取json文件Or文本文件
 * 
 * @author yushen
 * 
 */
public class JSONOrTextOut {

	public static void main(String[] args) {
		System.out.println(getJSONObject("C:/Users/yushen/Documents/Tencent Files/1251767927/FileRecv/网格1/10级.txt"));
	}

	// 读取jsonObejct
	public static JSONObject getJSONObject(String url) {
		JSONObject jo = new JSONObject();
		StringBuilder result = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new FileInputStream(url), "UTF-8"));
			String s = null;
			while ((s = br.readLine()) != null) {// 使用readLine方法,一次读一行
				result.append(System.lineSeparator() + s);
			}
			br.close();
			jo = JSONObject.parseObject(result.toString());

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// 构造一个BufferedReader类来读取文件

		return jo;
	}

	// 读取jsonArray
	public static JSONArray getJSONArray(String url) {
		JSONArray jo = new JSONArray();
		StringBuilder result = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new FileInputStream(url), "UTF-8"));
			String s = null;
			while ((s = br.readLine()) != null) {// 使用readLine方法,一次读一行
				result.append(System.lineSeparator() + s);
			}
			br.close();
			jo = JSONArray.parseArray(result.toString());

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// 构造一个BufferedReader类来读取文件

		return jo;
	}
}

 

你可能感兴趣的:(java)