195.m1-读取本地数据

读取本地数据,首先需要获取到本地数据的路径,然后读取数据中的数据,获取第一条数据,判断当前的数据是否国企,没有过期就直接读取

package com.ldw.market.protocol;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.StringWriter;

import com.ldw.market.http.HttpHelper;
import com.ldw.market.http.HttpHelper.HttpResult;
import com.ldw.market.utils.FileUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseStream;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.IOUtils;

public class HomeProtocal {

	//请求服务器数据,参数index,可以分批加载
	public void load(int index){
		
		//从本地请求数据
		String json = loadLocal(index);
		//返回的数据是json
		if(json == null){
			json = loadServer(index);
			//保存到本地
			if(json != null){
				saveLocal(json, index);
			}
		}else{
			System.out.println("使用了本地缓存");
		}
		//json不为空,就解析json
		if(json != null){
			parseJson(json);
		}
	}

	//解析json数据
	private void parseJson(String json) {
		// TODO Auto-generated method stub
		
	}

	//将json保存在本地:方法1把整个json文件写到一个本地文件中,方法2吧每条数据都摘出来保存在数据库中
	private void saveLocal(String json, int index) {
		//创建一个buffer
		BufferedWriter bw = null;
		try {
			File dir=FileUtils.getCacheDir();
			//创建一个文件
			File file = new File(dir, "home_" + index); // /mnt/sdcard/market/cache/home_0
			FileWriter fw = new FileWriter(file);
			 bw = new BufferedWriter(fw);
			//在第一行写一个过期时间 
			bw.write(System.currentTimeMillis() + 1000 * 100 + "");
			bw.newLine();// 换行
			bw.write(json);// 把整个json文件保存起来
			bw.flush();
			bw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			IOUtils.closeQuietly(bw);
		}
		
	}

	//从服务器请求json数据
	private String loadServer(int index) {
		//请求地址http://127.0.0.1:8090/home?index=1
		HttpResult httpResult = HttpHelper.get(HttpHelper.URL +"home"
				+ "?index=" + index); 
		//得到结果
		String json = httpResult.getString();
		//System.out.println(json);
		return json;
	}

	//加载本地保存的数据
	private String loadLocal(int index) {
		// 如果发现时间过期了,就不用本地的缓存
		File dir=FileUtils.getCacheDir();// 获取缓存所在的文件夹
		//得到缓存文件
		File file = new File(dir, "home_" + index); 
		try {
			FileReader fr=new FileReader(file);
			BufferedReader br=new BufferedReader(fr);
			//获取过期时间
			long outOfDate = Long.parseLong(br.readLine());
			//判断是否过期,
			if(System.currentTimeMillis()>outOfDate){
				return null;
			}else{
				String str=null;
				StringWriter sw=new StringWriter();
				while((str=br.readLine())!=null){
				
					sw.write(str);
				}
				return sw.toString();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值