android項目創建xml和存儲xml文件

學安卓複習java基礎

因爲項目需要刷新出昨天的文章,因此之前點擊一份電子雜誌,創建一個新的xml文件的方式就不對了,因爲電子雜誌不同於新聞,不會時時更新,因此一條更新一次,所以我需要每天下載一份它的RSS 源的xml文件到項目裏(曾經居然想下載到手機的sd卡里),文件命名格式以時間加上雜誌名,那麼我每天需要創建這些xml,在項目下創建文件可以在files和cache中創建,我選擇在files下創建。
                File file1 = null,file2=null,file3=null,file4=null;
		Date date2 = new Date();
		SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMdd");
		//獲取項目文件files的目錄
		File tempFile = this.getFilesDir();
		String yygypathstr = tempFile.toString();
		//文件命名格式爲以時間(年月日)+資源名
		file1 = new File(yygypathstr, (format2.format(date2)+"VICE中國"+ ".xml"));
		file2 = new File(yygypathstr, (format2.format(date2)+"設計癖"+ ".xml"));
		file3 = new File(yygypathstr, (format2.format(date2)+"知乎"+ ".xml"));
		file4 = new File(yygypathstr, (format2.format(date2)+"豆瓣一刻"+ ".xml"));
		//如果文件不存在,才創建
		if (!file1.exists() && !file2.exists() && !file3.exists() && !file4.exists()) {
			try {
				file1.createNewFile();
				file2.createNewFile();
				file3.createNewFile();
				file4.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		

這個放在第一個activity中進行判斷。創建好了之後,需要往這裏面些數據,如果文件不爲空且可以和RSS源連接上,就寫入數據,我們需要往當天的那份雜誌不爲空的xml文件寫入數據,用到循環判斷。
                        Date date = new Date();
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
			String paperTitleName=format.format(date)+title+ ".xml";
			File file=null;
			
			File fileXml=new File(xmlPath.toString());
			File[] tempList = fileXml.listFiles();
			//點擊那一份雜誌,找到這份雜誌的當天xml賦給file
			for (int i = 0; i < tempList.length; i++) {
				if (paperTitleName.equals(tempList[i].getName())) {
					file=tempList[i];
				}
			}
如果不爲空就不存入數據
                        HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(RSS_URL);
			try {
				HttpResponse response = client.execute(get);
				if (response.getStatusLine().getStatusCode() == 200 && file.length()==0) {
					InputStream inputStream = response.getEntity().getContent();

					FileOutputStream fos = new FileOutputStream(file);
					int byteread = 0;
					byte[] buffer = new byte[1024];
					while ((byteread = inputStream.read(buffer)) != -1) {

						fos.write(buffer, 0, byteread);
					}
					fos.flush();
					fos.close();
					inputStream.close();
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
存入數據之後,開始解析xml文件讀取數據,方法和我之前寫的如何讀取xml的方法一樣。明天我將完成如何向下滑動,刷新出昨天的文章。




發佈了79 篇原創文章 · 獲贊 42 · 訪問量 35萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章