天气预报 文件操作

package com.lolaage.tool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xmlpull.v1.XmlPullParser;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.util.Xml;

import com.lolaage.app.application.PETApplication;
import com.lolaage.entity.WeatherInfo;
import com.lolaage.entity.WeatherNextInfo;

public class WeatherUtil {

private static WeatherUtil instance;
private String cacheFile;//存放天气缓存的文件名
private Map<String, WeatherInfo> weather;//按城市区分保存天气缓存
private static String USER_AGENT = "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.11) Gecko/20101031 Gentoo Firefox/3.6.11";

private WeatherUtil(){
cacheFile = PETApplication.getContext().getCacheDir().toString() + "/weathers";
}
public static WeatherUtil getInstance(){
if(instance == null){
instance = new WeatherUtil();
}
return instance;
}
/**
* 保存天气缓存
* @param weather
* @return:保存结果
*/
public boolean saveWeathers(Map<String, WeatherInfo> weather){
this.weather = weather;
return save(weather,cacheFile);
}
private boolean save(Object obj,String path) {
FileOutputStream outputStream = null;
ObjectOutputStream objectOutputStream = null;
try {
outputStream = new FileOutputStream(path);
//ObjectOutputStream 将基本数据类型和图形写入 OutputStream,并且对网络数据所保存的对象要实现序列化
objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(obj);
objectOutputStream.flush();
objectOutputStream.close();
return true;
} catch (Exception e) {
return false;
}finally{
if(outputStream != null || objectOutputStream != null){
try {
objectOutputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 获取缓存中的天气
* @return
*/
public WeatherInfo loadWeather(){
WeatherInfo info = null;
if(weather == null){
weather = (Map<String, WeatherInfo>) load(cacheFile);
}
if(weather != null){
//获取缓存天气城市的遍历器
Iterator<String> iterator = weather.keySet().iterator();
while (iterator.hasNext()) {
String city = iterator.next();//获取节点
info = weather.get(city);
info.city = city;
}
}else {
weather = new HashMap<String, WeatherInfo>();
}
return info;
}
private Object load(String path){
Object object = null;
File file = new File(path);
FileInputStream isFileInputStream = null;
ObjectInputStream objectInputStream = null;
try {
if(file.exists()){
isFileInputStream = new FileInputStream(file);
objectInputStream = new ObjectInputStream(isFileInputStream);
object = objectInputStream.readObject();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(isFileInputStream != null || objectInputStream != null){
objectInputStream.close();
isFileInputStream.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return object;
}
/**
* 清空缓存
*/
public void clearCacheWeather(){
new File(cacheFile).delete();
}
/**
* 取得天气信息
* @param url
*/
public static WeatherInfo getWeatherMes(String url,double latitude,double longitude){
WeatherInfo weatherInfo = new WeatherInfo();
DefaultHttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet(url);
//设置请求头(用来解决网络获取数据乱码问题)
request.setHeader("User-Agent",USER_AGENT);
request.setHeader("Accept-Encoding", "gzip,deflate");

HttpResponse response = null;
InputStream inputStream = null;
try {
response = client.execute(request);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();

//判断返回的请求头(解决乱码)
Header header = response.getFirstHeader("Content-Encoding");
if(header != null && header.getValue().toLowerCase().indexOf("gzip") > -1){
inputStream = new GZIPInputStream(inputStream);
}
//解析
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.parse(new InputSource(inputStream));
NodeList nodeList = document.getElementsByTagName("forecast_information");
//取得当天日期
String date = nodeList.item(0).getChildNodes().item(4).getAttributes().item(0).getNodeValue();
NodeList nodeList2 = document.getElementsByTagName("current_conditions");
//取得当天天气、湿度、图片、风速
String condition = nodeList2.item(0).getChildNodes().item(0).getAttributes().item(0).getNodeValue();
String humidity = nodeList2.item(0).getChildNodes().item(3).getAttributes().item(0).getNodeValue();
String icon = nodeList2.item(0).getChildNodes().item(4).getAttributes().item(0).getNodeValue();
String wind = nodeList2.item(0).getChildNodes().item(5).getAttributes().item(0).getNodeValue();

NodeList nodeList3 = document.getElementsByTagName("forecast_conditions");
//取得当天的星期、温度
String week = nodeList3.item(0).getChildNodes().item(0).getAttributes().item(0).getNodeValue();
String low = nodeList3.item(0).getChildNodes().item(1).getAttributes().item(0).getNodeValue();
String high = nodeList3.item(0).getChildNodes().item(2).getAttributes().item(0).getNodeValue();
weatherInfo.city = getCityForlola(Constant.CITY_API, latitude, longitude);
weatherInfo.date = date;
weatherInfo.condition = condition;
weatherInfo.humidity = humidity;
weatherInfo.icon = icon;
weatherInfo.wind = wind;
weatherInfo.week = week;
weatherInfo.highTemp = high;
weatherInfo.lowTemp = low;

WeatherNextInfo nextInfo;
//取得今后3天的天气情况
for (int i = 1; i < nodeList3.getLength(); i++) {
nextInfo = new WeatherNextInfo();
nextInfo.week = nodeList3.item(i).getChildNodes().item(0).getAttributes().item(0).getNodeValue();
nextInfo.low = nodeList3.item(i).getChildNodes().item(1).getAttributes().item(0).getNodeValue();
nextInfo.high = nodeList3.item(i).getChildNodes().item(2).getAttributes().item(0).getNodeValue();
nextInfo.icon = nodeList3.item(i).getChildNodes().item(3).getAttributes().item(0).getNodeValue();
nextInfo.condition = nodeList3.item(i).getChildNodes().item(4).getAttributes().item(0).getNodeValue();
weatherInfo.nextWeatherList.add(nextInfo);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(inputStream != null){
inputStream.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return weatherInfo;
}
/**
* 根据经纬度解析城市
* @param url
* @param latitude
* @param longitude
* @return
*/
public static String getCityForlola(String url,double latitude,double longitude){
String city = "";
String formatUrl = String.format(url, latitude,longitude);
DefaultHttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet(formatUrl);
request.setHeader("User-Agent",USER_AGENT);
request.setHeader("Accept-Encoding","gzip,deflate");

HttpResponse response = null;
InputStream inputStream = null;
try {
response = client.execute(request);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();

Header header = response.getFirstHeader("Content-Encoding");
if(header != null && header.getValue().toLowerCase().indexOf("gzip") > -1){
inputStream = new GZIPInputStream(inputStream);
}

XmlPullParser parser = Xml.newPullParser();
parser.setInput(inputStream, "UTF-8");
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_TAG://开始解析标签元素
if(parser.getName().equalsIgnoreCase("LocalityName")){
city = parser.nextText();//取得节点后面的text值
}
break;

case XmlPullParser.END_TAG:
break;
}
eventType = parser.next();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(inputStream != null){
inputStream.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return city;
}
/**
* 日期格式化
* @param str
* @return
* @throws ParseException
*/
public static String dateFormat(String str){
Date date = null;
SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");
if(str != null && !"".equals(str)){
try {
date = df.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年mm月dd日");
return sdf.format(date);
}
/**
*
* @param str
* @return
*/
public static String weekFormat(String str){
String week = "";
if(str != null && !"".equals(str)){
if(str.startsWith("周")){
week = str.replaceFirst("周", "星期");
}
}
return week;
}
/**
* 返回天气图标
* @param iconUrl
* @return
*/
public static Bitmap returnIcon(String iconUrl){
URL imgUrl = null;
Bitmap bp = null;
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
imgUrl = new URL(iconUrl);
connection = (HttpURLConnection) imgUrl.openConnection();
connection.setDoInput(true);
connection.connect();
inputStream = connection.getInputStream();
bp = BitmapFactory.decodeStream(inputStream);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(inputStream != null || connection != null){
inputStream.close();
connection.disconnect();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return bp;
}

}
/**
* 天气预报访问接口
*/
public static final String WEATHER_URL = "http://www.google.com/ig/api?hl=zh-cn&weather";
/**
* 获取城市名访问接口
*/
public static final String CITY_API = "http://ditu.google.cn/maps/geo?output=xml&key=abc&q=%s,%s";
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值