1. 程式人生 > >天氣介面的IO讀寫操作

天氣介面的IO讀寫操作

前段時間碼程式碼用到過的,涉及到:1,介面的遠端呼叫;2,IO流的讀寫;3,xml報文的解析等;這裡簡單做個整理,再用可以直接拿過來用了,so不解釋直接上程式碼。

需求:根據天氣介面獲取城市上海當前天氣情況,並將xml結果儲存至本地指定位置,隨後解析xml資源以獲取浦東新區對應的天氣情況;

天氣介面: http://flash.weather.com.cn/wmaps/xml/shanghai.xml

直接上程式碼: 

public class Queryweather {
	
	public static void main(String[] args) {
		Queryweather query = new Queryweather();
		String cityName = "shanghai";
		String filePath = "C:/Users/admin/Desktop/test";
		query.weatherHandle(cityName, filePath);
	}
	
	public void weatherHandle(String cityName, String filePath) {
		Queryweather query = new Queryweather();
		String resourceUrl = "http://flash.weather.com.cn/wmaps/xml/"+cityName+".xml";
		//查詢天氣介面,獲取響應報文
		String response = query.readWeatherXML(resourceUrl);
		byte[] bfile = response.getBytes();
		String fileName = cityName+".xml";
		//將報文寫進本地指定位置filePath
		query.writeWeatherXML(bfile, filePath, fileName);
		//讀取天氣資源
		Map<String, Weather> weathers = query.readXML(filePath+"/"+fileName);
		Weather weather = query.queryWeather(weathers, "浦東新區");
		System.out.println(weather);
	}
	
	public Weather queryWeather(Map<String, Weather> weathers, String centername) {
		Weather weather = weathers.get(centername);
		return weather;
	}
	
	public Map<String, Weather> readXML(String fileUrl) {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(fileUrl))));
			SAXReader reader = new SAXReader();
			Document doc = reader.read(br);
			Element root = doc.getRootElement();
			java.util.Iterator<Element> iter =  root.elementIterator();
			Map<String, Weather> weathers = new HashMap<String, Weather>();
			while(iter.hasNext()){
				Element ele = iter.next();
				String centername = ele.attributeValue("centername");
				String stateDetailed = ele.attributeValue("stateDetailed");//天氣情況
				String tem1 = ele.attributeValue("tem1");//最低溫
				String tem2 = ele.attributeValue("tem2");//最高溫
				String temNow = ele.attributeValue("temNow");
				String windState = ele.attributeValue("windState");
				Weather weather = new Weather(centername, stateDetailed, tem1, tem2, temNow, windState);
				weathers.put(centername, weather);
			}
			return weathers;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 根據資源路徑讀取檔案
	 * @param resourceUrl
	 * @return
	 */
	public String readWeatherXML(String resourceUrl) {
		BufferedReader br = null;
		try {
			URL url = new URL(resourceUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			br = new BufferedReader(new InputStreamReader(is));
			String str = null;
			String response = "";
			while((str = br.readLine()) != null){
				response += str;
			}
			System.out.println(response);
			return response;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 將二進位制資源寫進指定檔案
	 * @param bfile
	 * @param filePath
	 * @param fileName
	 */
	public void writeWeatherXML(byte[] bfile, String filePath, String fileName) {
		//1,建立資料夾和檔案
		File dir = new File(filePath);
		if(!dir.exists()){
			dir.mkdirs();
		}
		File file = new File(filePath+File.separator+fileName);
		BufferedOutputStream bos = null;
		//2,將二進位制資源寫入file
		try {
			bos = new BufferedOutputStream(new FileOutputStream(file));
			bos.write(bfile);
			System.out.println("檔案寫入ok");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

對應的Weather類:

public class Weather {
	private String centername;
	private String stateDetailed;
	private String tem1;
	private String tem2;
	private String temNow;
	private String windState;
	
	public Weather(String centername, String stateDetailed, String tem1, String tem2, String temNow, String windState) {
		super();
		this.centername = centername;
		this.stateDetailed = stateDetailed;
		this.tem1 = tem1;
		this.tem2 = tem2;
		this.temNow = temNow;
		this.windState = windState;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((centername == null) ? 0 : centername.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Weather other = (Weather) obj;
		if (centername == null) {
			if (other.centername != null)
				return false;
		} else if (!centername.equals(other.centername))
			return false;
		return true;
	}
	@Override
	public String toString() {
		return "Weather [centername=" + centername + ", stateDetailed=" + stateDetailed + ", 最高溫=" + tem1 + ", 最低溫="
				+ tem2 + ", 當前溫度=" + temNow + ", windState=" + windState + "]";
	}
	public String getCentername() {
		return centername;
	}
	public void setCentername(String centername) {
		this.centername = centername;
	}
	public String getStateDetailed() {
		return stateDetailed;
	}
	public void setStateDetailed(String stateDetailed) {
		this.stateDetailed = stateDetailed;
	}
	public String getTem1() {
		return tem1;
	}
	public void setTem1(String tem1) {
		this.tem1 = tem1;
	}
	public String getTem2() {
		return tem2;
	}
	public void setTem2(String tem2) {
		this.tem2 = tem2;
	}
	public String getTemNow() {
		return temNow;
	}
	public void setTemNow(String temNow) {
		this.temNow = temNow;
	}
	public String getWindState() {
		return windState;
	}
	public void setWindState(String windState) {
		this.windState = windState;
	}
}

 

任北風吹,做最好的自己!--Jonathan  2018/10/5