本文實例講述了Android數據持久化之讀寫SD卡中內容的方法。分享給大家供大家參考,具體如下:
前面文章里講的那三個方法:openFileOutput
、openFileInput
雖然都能通過流對象OutputStream和InputStream可以處理任意文件中的數據,但與 SharedPreferences
一樣,只能在手機內存的指定目錄下建立文件,因此,在實際的開發使用中有很大的局限性,那么在這一節中,我們來看一個比較高級的方法來實現數據的持久化——讀寫SD卡上的內容。
——讀取assets目錄中的文件
android中的文件夾assets存放的是二進制的文件格式,比如音頻、視頻、圖片等,但該目錄下的文件不會被R.java文件索引到,如果想讀取該目錄下的文件還需要借助AssetManager對象。
代碼如下:
/** * 將圖片文件保存到SD卡的根目錄下 * * 雖然確定SD卡的路徑是可以直接使用"/sdcard"的,但在實際開發中建議使用:android.os.Environment.getExternalStorageDirectory() * 方法獲得SD卡的路徑,這樣一旦系統改變了路徑,應用程序會立刻獲得最新的SD卡的路徑,這樣做會使程序更健壯。 */ public void writeToSD() { try { //創建用于將圖片保存到SD卡上的FileOutputStream對象 FileOutputStream fos = new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + "/image.jpg"); //打開assets目錄下的image.jpg文件,并返回InputStream對象 InputStream is = getResources().getAssets().open("image.jpg"); //定義一個byte數組,用來保存每次向SD卡中文件寫入的數據,最多8k byte[] buffer = new byte[8192]; int count = 0; //循環寫入數據 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開始,默認不允許向SD卡中寫文件,因此要添加權限,在AndroidManifest.xml文件添加如下代碼:
<!-- 獲取寫權限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
那么這個文件保存到哪了呢?在Eclipse中進入File Explorer 面板,選中/data/app目錄下的該程序的APK文件,將其導出到桌面上或者其他地方,解壓后進入assets目錄可看見剛才保存的圖片。
由于assets文件夾下的文件是被打包進apk文件中的,所以assets目錄中的文件只能讀,不能寫。
——SAX引擎讀取XML文件
原理:
android SDK 本身提供了操作XML文件的類庫,這就是SAX,使用SAX處理XML需要一個Handler對象,一般會使用:org.xml.sax.helpers.DefaultHandler 的子類來創建Handler對象。SAX技術處理XML文件時并不是一次性的把XML文件裝入內存,而是一邊讀一邊解析,因此,就需要如下的五個分析點(分析事件):
1、開始分析XML文件:對應方法 DefaultHandler.startDocument 可以在該方法中做一些初始化的工作
2、開始處理每一個XML標簽,即每個標簽對的起始標簽:對應方法 startElement 該方法可以獲取當前標簽的名稱、屬性的相關信息
3、處理完每一個XML標簽,即每個標簽對的結束標簽:對應方法 endElement 獲得當前處理的標簽的全部信息
4、處理完XML文件,即處理完了整個XML文件的內容時,就到這一步了,對應方法:endDocument
5、讀取字符分析點,是對上述獲取到的XML文件的全部內容的處理,這一步很重要,對應方法:characters 用來處理獲取到的XML文件中的內容,即保存XML標簽中的內容。
如下是對上面五點的應用,將XML文件轉換成java對象:
首先在/res/raw 下創建一個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文件,創建list對象用于保存分析完的product對象 products = new ArrayList<Product>(); super.startDocument(); } /** * 開始分析XML中的標簽 */ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (localName.equals("product")) { // 如果開始分析的是<product>標簽,創建一個product對象 product = new Product(); } super.startElement(uri, localName, qName, attributes); } /** * 分析完了XML中的標簽 * 使用sb中的值為product對象中的屬性賦值 */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (localName.equals("product")) { // 處理完<product>標簽后,將product對象添加到products中 products.add(product); } else if (localName.equals("id")) { // 設置id屬性值 product.setId(Integer.parseInt(sb.toString().trim())); // 將保存標簽內容的緩存區清空 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文件中的內容 */ @Override public void characters(char[] ch, int start, int length) throws SAXException { // 將SAX掃描到的內容保存到sb變量中 sb.append(ch, start, length); super.characters(ch, start, length); } }
下面的就是將xml文件轉化成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(); } // 將轉換后得到的java對象的內容輸出 List<Product> products = xml2product.getProduct(); String msg = "total" + products.size() + "\n"; for (Product product : products) { msg += "id:" + product.getId() + "產品名:" + product.getName() + "價格" + product.getPrice() + "\n"; } new AlertDialog.Builder(this).setTitle("產品信息").setMessage(msg) .setPositiveButton("關閉", 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; } }
更多關于Android相關內容感興趣的讀者可查看本站專題:《Android編程開發之SD卡操作方法匯總》、《Android文件操作技巧匯總》、《Android數據庫操作技巧總結》、《Android編程之activity操作技巧總結》、《Android開發入門與進階教程》、《Android資源操作技巧匯總》、《Android視圖View技巧總結》及《Android控件用法總結》
希望本文所述對大家Android程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。