溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android數(shù)據(jù)持久化之讀寫SD卡中內(nèi)容的方法詳解

發(fā)布時間:2020-09-13 21:10:26 來源:腳本之家 閱讀:159 作者:android小豬 欄目:移動開發(fā)

本文實例講述了Android數(shù)據(jù)持久化之讀寫SD卡中內(nèi)容的方法。分享給大家供大家參考,具體如下:

前面文章里講的那三個方法:openFileOutput 、openFileInput 雖然都能通過流對象OutputStreamInputStream可以處理任意文件中的數(shù)據(jù),但與 SharedPreferences 一樣,只能在手機內(nèi)存的指定目錄下建立文件,因此,在實際的開發(fā)使用中有很大的局限性,那么在這一節(jié)中,我們來看一個比較高級的方法來實現(xiàn)數(shù)據(jù)的持久化——讀寫SD卡上的內(nèi)容。

——讀取assets目錄中的文件

android中的文件夾assets存放的是二進(jìn)制的文件格式,比如音頻、視頻、圖片等,但該目錄下的文件不會被R.java文件索引到,如果想讀取該目錄下的文件還需要借助AssetManager對象。

代碼如下:

/**
* 將圖片文件保存到SD卡的根目錄下
*
* 雖然確定SD卡的路徑是可以直接使用"/sdcard"的,但在實際開發(fā)中建議使用:android.os.Environment.getExternalStorageDirectory()
* 方法獲得SD卡的路徑,這樣一旦系統(tǒng)改變了路徑,應(yīng)用程序會立刻獲得最新的SD卡的路徑,這樣做會使程序更健壯。
*/
public void writeToSD() {
    try {
      //創(chuàng)建用于將圖片保存到SD卡上的FileOutputStream對象
      FileOutputStream fos = new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + "/image.jpg");
      //打開assets目錄下的image.jpg文件,并返回InputStream對象
      InputStream is = getResources().getAssets().open("image.jpg");
      //定義一個byte數(shù)組,用來保存每次向SD卡中文件寫入的數(shù)據(jù),最多8k
      byte[] buffer = new byte[8192];
      int count = 0;
      //循環(huán)寫入數(shù)據(jù)
      while((count = is.read(buffer)) != -1)
      {
        fos.write(buffer, 0, count);
      }
      fos.close();
      is.close();
      Toast.makeText(this, "已成功將圖片保存在SD卡中", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
}
/**
* 從SD卡中讀取圖片文件
* @throws IOException
*/
public void readFromSD() throws IOException{
    //指定SD卡中的圖像文件名
    String fileName = android.os.Environment.getExternalStorageState() + "image.jpg";
    //判斷文件圖片是否存在
    if (!new File(fileName).exists()) {
      Toast.makeText(this, "沒有要找的圖片文件,未裝入", Toast.LENGTH_SHORT).show();
      return;
    }
    image = (ImageView) findViewById(R.id.image);
    FileInputStream fis = new FileInputStream(fileName);
    //從文件的輸入流裝載Bimap對象
    Bitmap bitmap = BitmapFactory.decodeStream(fis);
    image.setImageBitmap(bitmap);
    fis.close();
}

從android2.x開始,默認(rèn)不允許向SD卡中寫文件,因此要添加權(quán)限,在AndroidManifest.xml文件添加如下代碼:

<!-- 獲取寫權(quán)限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

那么這個文件保存到哪了呢?在Eclipse中進(jìn)入File Explorer 面板,選中/data/app目錄下的該程序的APK文件,將其導(dǎo)出到桌面上或者其他地方,解壓后進(jìn)入assets目錄可看見剛才保存的圖片。

由于assets文件夾下的文件是被打包進(jìn)apk文件中的,所以assets目錄中的文件只能讀,不能寫。

——SAX引擎讀取XML文件

原理:

android SDK 本身提供了操作XML文件的類庫,這就是SAX,使用SAX處理XML需要一個Handler對象,一般會使用:org.xml.sax.helpers.DefaultHandler 的子類來創(chuàng)建Handler對象。SAX技術(shù)處理XML文件時并不是一次性的把XML文件裝入內(nèi)存,而是一邊讀一邊解析,因此,就需要如下的五個分析點(分析事件):

1、開始分析XML文件:對應(yīng)方法 DefaultHandler.startDocument  可以在該方法中做一些初始化的工作

2、開始處理每一個XML標(biāo)簽,即每個標(biāo)簽對的起始標(biāo)簽:對應(yīng)方法 startElement  該方法可以獲取當(dāng)前標(biāo)簽的名稱、屬性的相關(guān)信息

3、處理完每一個XML標(biāo)簽,即每個標(biāo)簽對的結(jié)束標(biāo)簽:對應(yīng)方法 endElement 獲得當(dāng)前處理的標(biāo)簽的全部信息

4、處理完XML文件,即處理完了整個XML文件的內(nèi)容時,就到這一步了,對應(yīng)方法:endDocument

5、讀取字符分析點,是對上述獲取到的XML文件的全部內(nèi)容的處理,這一步很重要,對應(yīng)方法:characters  用來處理獲取到的XML文件中的內(nèi)容,即保存XML標(biāo)簽中的內(nèi)容。

如下是對上面五點的應(yīng)用,將XML文件轉(zhuǎn)換成java對象:

首先在/res/raw 下創(chuàng)建一個wxml文件:

<?xml version="1.0" encoding="utf-8"?>
<products>
  <product>
    <id>1</id>
    <name>電腦</name>
    <price>3088</price>
  </product>
  <product>
    <id>2</id>
    <name>微波爐</name>
    <price>2500</price>
  </product>
  <product>
    <id>3</id>
    <name>洗衣機</name>
    <price>1088</price>
  </product>
</products>

定義一個product類:

package com.example.data_io_xmltojava;
public class Product {
  int id;
  String name;
  int price;
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getPrice() {
    return price;
  }
  public void setPrice(int price) {
    this.price = price;
  }
}

下面是XML2Product類,是DefaultHandler的子類,這個類是整個程序中最重要最核心的類:

package com.example.data_io_xmltojava;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class XML2Product extends DefaultHandler {
  List<Product> products;
  Product product;
  StringBuffer sb = new StringBuffer();
  public List<Product> getProduct() {
    return products;
  }
  /**
   * 開始分析XML文件
   */
  @Override
  public void startDocument() throws SAXException {
    // 開始分析XML文件,創(chuàng)建list對象用于保存分析完的product對象
    products = new ArrayList<Product>();
    super.startDocument();
  }
  /**
   * 開始分析XML中的標(biāo)簽
   */
  @Override
  public void startElement(String uri, String localName, String qName,
      Attributes attributes) throws SAXException {
    if (localName.equals("product")) {
      // 如果開始分析的是<product>標(biāo)簽,創(chuàng)建一個product對象
      product = new Product();
    }
    super.startElement(uri, localName, qName, attributes);
  }
  /**
   * 分析完了XML中的標(biāo)簽
   * 使用sb中的值為product對象中的屬性賦值
   */
  @Override
  public void endElement(String uri, String localName, String qName)
      throws SAXException {
    if (localName.equals("product")) {
      // 處理完<product>標(biāo)簽后,將product對象添加到products中
      products.add(product);
    } else if (localName.equals("id")) {
      // 設(shè)置id屬性值
      product.setId(Integer.parseInt(sb.toString().trim()));
      // 將保存標(biāo)簽內(nèi)容的緩存區(qū)清空
      sb.setLength(0);
    } else if (localName.equals("name")) {
      product.setName(sb.toString().trim());
      sb.setLength(0);
    } else if (localName.equals("price")) {
      product.setPrice(Integer.parseInt(sb.toString().trim()));
      sb.setLength(0);
    }
    super.endElement(uri, localName, qName);
  }
  /**
   * 分析完了XML文件
   */
  @Override
  public void endDocument() throws SAXException {
    super.endDocument();
  }
  /**
   * 處理SAX讀取到的XML文件中的內(nèi)容
   */
  @Override
  public void characters(char[] ch, int start, int length)
      throws SAXException {
    // 將SAX掃描到的內(nèi)容保存到sb變量中
    sb.append(ch, start, length);
    super.characters(ch, start, length);
  }
}

下面的就是將xml文件轉(zhuǎn)化成java對象的類了:

package com.example.data_io_xmltojava;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.xml.sax.SAXException;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.util.Xml;
import android.view.Menu;
public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // 獲得 /res/raw/products.xml文件中InputStream對象
    InputStream is = getResources().openRawResource(R.raw.products);
    XML2Product xml2product = new XML2Product();
    try {
      // 開始分析products.xml文件(解析)
      android.util.Xml.parse(is, Xml.Encoding.UTF_8, xml2product);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SAXException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    // 將轉(zhuǎn)換后得到的java對象的內(nèi)容輸出
    List<Product> products = xml2product.getProduct();
    String msg = "total" + products.size() + "\n";
    for (Product product : products) {
      msg += "id:" + product.getId() + "產(chǎn)品名:" + product.getName() + "價格"
          + product.getPrice() + "\n";
    }
    new AlertDialog.Builder(this).setTitle("產(chǎn)品信息").setMessage(msg)
        .setPositiveButton("關(guān)閉", null).show();
  }
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }
}

更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android編程開發(fā)之SD卡操作方法匯總》、《Android文件操作技巧匯總》、《Android數(shù)據(jù)庫操作技巧總結(jié)》、《Android編程之a(chǎn)ctivity操作技巧總結(jié)》、《Android開發(fā)入門與進(jìn)階教程》、《Android資源操作技巧匯總》、《Android視圖View技巧總結(jié)》及《Android控件用法總結(jié)》

希望本文所述對大家Android程序設(shè)計有所幫助。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI