Mars Chen影片XML程式碼實現
注意:
1.製作xml檔案時候特別小心回車和Tab鍵,在解析程式,把他們也當做是有效字元,因此輸出結果會跟預期不一樣.
2.在從網上下載檔案時讀入檔案流時候,需要新增StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
要不然下載檔案會報錯,下載檔案失敗。這個函式要求在API 9以上才可以使用,因此注意需要在AndroidManifest中配置
<uses-sdk android:minSdkVersion="9" android:targetSdkVersion="18" />
android:minSdkVersion要在9以上,如果為8,則系統將報錯,無法編譯。
3. 使筆記本除錯Eclipse程式,有時候很多快捷鍵用不了是因為Eclipse很多快捷鍵跟筆記本的快捷鍵衝突,而系統優先系統的快捷鍵。加入一個外插鍵盤,eclipse快捷鍵就都能用了。
(1)AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="" package="com.example.xml" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.xml.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> </manifest>
(2)FileUtils.java
package com.example.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.os.Environment; public class FileUtils { private String SDPATH; public String getSDPATH() { return SDPATH; } public FileUtils() { SDPATH = Environment.getExternalStorageDirectory() + "/"; } public File createSDFile(String fileName) throws IOException { File file = new File(SDPATH + fileName); file.createNewFile(); return file; } public File createSDDir(String dirName) { File dir = new File(SDPATH + dirName); dir.mkdir(); return dir; } public boolean isFileExist(String strFileName) { File file = new File(SDPATH + strFileName); return file.exists(); } public File write2SDFromInput(String path, String fileName, InputStream input) { File file = null; OutputStream output = null; try { createSDDir(path); file = createSDFile(path + fileName); output = new FileOutputStream(file); byte buffer[] = new byte[4 * 1024]; while ((input.read(buffer)) != -1) { output.write(buffer); } output.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { output.close(); } catch (Exception e) { e.printStackTrace(); } } return file; } }
(3)HttpDownloader.java
package com.example.utils; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.os.StrictMode; public class HttpDownloader { private URL url = null; public String download(String strUrl){ StringBuffer sb = new StringBuffer(); String line = null; BufferedReader buffer = null; try{ StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build()); url = new URL(strUrl); HttpURLConnection urlConn = (HttpURLConnection)url.openConnection(); buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); while ((line = buffer.readLine()) != null){ sb.append(line); } }catch (Exception e){ e.printStackTrace(); }finally{ try{ buffer.close(); }catch (Exception e){ e.printStackTrace(); } } return sb.toString(); } /** * * @param strUrl * @param strPath * @param strFileName * @return * * -1: error occurs when downloading; 0: downloaded successfully; 1: the downloading file already exists */ public int downFile(String strUrl, String strPath, String strFileName){ InputStream inputStream = null; try{ FileUtils fileUtils = new FileUtils(); if (fileUtils.isFileExist(strPath + strFileName)){ return 1; } else { inputStream = getInputStreamFromUrl(strUrl); File resultFile = fileUtils.write2SDFromInput(strPath, strFileName, inputStream); if (resultFile == null){ return -1; } } } catch (Exception e){ e.printStackTrace(); return -1; } finally{ try { inputStream.close(); } catch (Exception e){ e.printStackTrace(); } } return 0; } public InputStream getInputStreamFromUrl(String strUrl) throws MalformedURLException, IOException{ StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build()); url = new URL(strUrl); HttpURLConnection urlConn = (HttpURLConnection)url.openConnection(); InputStream inputStream = urlConn.getInputStream(); return inputStream; } }
(4)MainActivity.java
package com.example.xml; import java.io.StringReader; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.Button; import com.example.utils.HttpDownloader; public class MainActivity extends Activity { private Button parseXML = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); parseXML = (Button)findViewById(R.id.parseXML); parseXML.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub HttpDownloader hd = new HttpDownloader(); String strResult = hd.download(""); System.out.println(strResult); try { //使用Simple API for XML (SAX) 讀取檔案 //相對於DOM一次性按節點模式全讀入記憶體,才能進行處理 //該類為邊讀邊處理,讀取操作可以隨時中斷,適合於超大型的xml檔案 SAXParserFactory factory = SAXParserFactory.newInstance(); XMLReader reader = factory.newSAXParser().getXMLReader(); reader.setContentHandler(new MyContentHandler()); reader.parse(new InputSource(new StringReader(strResult))); } catch (Exception e) { e.printStackTrace(); } } }); } @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; } }
(5)MyContentHandler.java
package com.example.xml; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; //這裡沒有實現contentHandler介面是因為我們不需要重寫所有介面函式 //我們採用繼承模式,只需將需要重新的函式實現即可 public class MyContentHandler extends DefaultHandler{ String name1, address1, money1, sex1, status1; String tagName; /* (non-Javadoc) * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int) */ @Override public void characters(char[] ch, int start, int length) throws SAXException { // TODO Auto-generated method stub if (tagName.equals("name")) { name1 = new String(ch, start, length); } if (tagName.equals("sex")) { sex1 = new String(ch, start, length); } if (tagName.equals("status")) { status1 = new String(ch, start, length); } if (tagName.equals("address")) { address1 = new String(ch, start, length); } if (tagName.equals("money")) { money1 = new String(ch, start, length); } } /* (non-Javadoc) * @see org.xml.sax.helpers.DefaultHandler#endDocument() */ @Override public void endDocument() throws SAXException { // TODO Auto-generated method stub System.out.println("-----------end----------"); } /* (non-Javadoc) * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { // TODO Auto-generated method stub if (localName.equals("worker")) { this.printOut(); } } //之所以列印不來這些名稱值,是因為在xml中存在"t"這種符號 //需要對檔案重新進行整理 public void printOut() { System.out.println("name: " + name1); System.out.println("sex: " + sex1); System.out.println("status: " + status1); System.out.println("address: " + address1); System.out.println("money: " + money1); } /* (non-Javadoc) * @see org.xml.sax.helpers.DefaultHandler#startDocument() */ @Override public void startDocument() throws SAXException { // TODO Auto-generated method stub System.out.println("------------begin-----------------"); } /* (non-Javadoc) * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // TODO Auto-generated method stub tagName = localName; if (localName.equals("worker")) { for (int i = 0; i < attributes.getLength(); i++) { System.out.println(attributes.getLocalName(i) + "=" + attributes.getValue(i)); } } } }
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/2144/viewspace-2816598/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- jquery實現的解析xml檔案程式碼例項jQueryXML
- 短影片程式原始碼,如何實現短影片的熱門頁面原始碼
- 影片直播系統原始碼,非同步處理實現程式碼分析原始碼非同步
- [PAT]1027. Colors in Mars (20)@Java實現Java
- jquery實現的讀取並解析xml檔案程式碼例項jQueryXML
- Android短影片系統硬編碼—實現音影片編碼(三)Android
- Android短影片系統硬編碼—實現音影片編碼(二)Android
- eKuiper 1.8.0 釋出:零程式碼實現影像/影片流的實時 AI 推理UIAI
- 從【抓包分析】到【程式碼實戰】,實現下載某破站影片(附原始碼)原始碼
- 短影片電商系統,編寫延遲訊息實現程式碼
- 【Dflying Chen 】.NET Framework原始碼釋出Framework原始碼
- JDom讀寫XML(程式碼)XML
- 影片直播原始碼,前端canvas動態驗證碼實現原始碼前端Canvas
- Promise 程式碼實現Promise
- 用XML實現程式語言間的互譯 (轉)XML
- 短影片app程式碼,如何實現聯表資料查詢和刪除?APP
- 實現彩色二維碼程式碼實
- Locust 程式碼指令碼實現指令碼
- [程式設計]Java實現解析抖音無水印影片程式設計Java
- app直播原始碼,xml實現由上而下的顏色漸變APP原始碼XML
- OutputStreamWriter介紹&程式碼實現和InputStreamReader介紹&程式碼實現
- javascript操作xml程式碼例項JavaScriptXML
- What time is it on Mars?
- 影片直播原始碼,js實現節流和防抖原始碼JS
- 如何實現程式碼高亮
- Tomcat程式碼實現Tomcat
- HashTable實現程式碼分享
- AsyncTask實現程式碼原理
- Kafka - SQL 程式碼實現KafkaSQL
- pygame播放影片並實現音影片同步GAM
- XML 程式設計思想:XML和語義:XML 會兌現其承諾嗎?(轉)XML程式設計
- Linklist程式碼實現以及程式碼解讀
- 影片直播app原始碼,純css實現橫向滾動APP原始碼CSS
- 短影片整套原始碼,如何實現冪等性校驗?原始碼
- Mars演算法實踐——人臉識別演算法
- DES原理及程式碼實現
- AES和DES程式碼實現
- vysor原理與程式碼實現