Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 項目中創建與存儲 XML 文件的實踐

編輯:關於 Android 程式設計

在做電子雜志類項目時,因為需要每天刷新出最新的文章,所以每次點擊都重新創建 XML 文件的方式並不合適。電子雜志不同於時時更新的新聞,它每天更新一次,因此更合理的做法是每天下載一份 RSS 源的 XML 文件到項目中,並以「日期 + 雜志名」的格式命名。這些文件可以創建在 files 或 cache 目錄下,本文選擇放在 files 中。

第一步:在項目 files 目錄下創建當天的 XML 文件

放在第一個 Activity 中進行判斷,若文件不存在則創建:

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) {
        e.printStackTrace();
    }
}

第二步:找到當天對應的 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];
    }
}

第三步:從 RSS 源下載內容並寫入文件

如果文件不為空且能連上 RSS 源,就寫入數據(若文件已有內容則跳過):

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) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

數據寫入完成後,就可以像讀取普通 XML 一樣解析文件並展示內容了。這樣每天只需下載並緩存一份最新的 RSS 數據,既減少了重複網絡請求,也保證了內容的時效性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved