从本地服务器下载文件与解析过程详解

1、建立工程:Mp3Player

2、在tomcat 服务器中准备相应的文件

   在D:\tomcat7.0\apache-tomcat-7.0.6-windows-x86\apache-tomcat-7.0.6\webapps (这是我自己电脑服务器的位置)下新建一个文件夹:mp3

  接下来在mp3里保存相应的文件:目录如下:

   其中最重要的一部分是resources.xml:   代码如下:

View Code
 1 <?xml version="1.0" encoding="ISO-8859-1"?>
2 <resources>
3 <resource>
4 <id>0001</id>
5 <mp3.name>1.mp3</mp3.name>
6 <mp3.size>5,033,984</mp3.size>
7 <lrc.name>1.lrc</lrc.name>
8 <lrc.size>4,096 </lrc.size>
9 </resource>
10 <resource>
11 <id>0002</id>
12 <mp3.name>2.mp3</mp3.name>
13 <mp3.size>3,768,320</mp3.size>
14 <lrc.name>2.lrc</lrc.name>
15 <lrc.size>4,096 </lrc.size>
16 </resource>
17 </resources>

3、编写主文件代码:

   (1)、布局文件:main.xml

View Code
 1          <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:orientation="vertical"
4 android:layout_width="fill_parent"
5 android:layout_height="fill_parent"
6 >
7 <LinearLayout
8 android:id="@+id/listLinearLayout"
9 android:layout_width="fill_parent"
10 android:layout_height="wrap_content"
11 android:orientation="vertical"
12 >
13 <ListView
14 android:id="@id/android:list"
15 android:layout_width="fill_parent"
16 android:layout_height="wrap_content"
17 android:drawSelectorOnTop="false"
18 android:scrollbars="vertical"
19 ></ListView>
20 </LinearLayout>
21 </LinearLayout>

  mp3_info_item.xml:  用于显示相应的信息

View Code
 1    <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 android:orientation="horizontal"
5 android:layout_width="fill_parent"
6 android:layout_height="fill_parent"
7 android:paddingLeft="10px"
8 android:paddingRight="10px"
9 android:paddingTop="1px"
10 android:paddingBottom="1px"
11 >
12 <TextView
13 android:id="@+id/mp3_name"
14 android:layout_width="180dip"
15 android:layout_height="wrap_content"
16 android:textSize="10pt"
17 />
18
19 <TextView
20 android:id="@+id/mp3_size"
21 android:layout_width="180dip"
22 android:layout_height="wrap_content"
23 android:textSize="10pt"
24 />
25 </LinearLayout>

  (2) 、资源文件: values\strings.xml

View Code
1 <?xml version="1.0" encoding="utf-8"?>
2 <resources>
3 <string name="hello">Hello World, Mp3ListActivity!</string>
4 <string name="app_name">mp3player</string>
5 <string name="mp3list_update">更新列表</string>
6 <string name="mp3list_about">关于</string>
7 </resources>

  (3)、主要逻辑代码:

      (1)、用于下载本地文件的代码:

package com.pisecs.download;

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.URL;

public class HttpDownloader {
   private URL url=null;
   
   public String download(String urlStr){
	   StringBuffer sb=new StringBuffer();
	   String line=null;
	   BufferedReader buffer=null;
	   try{
		   url=new URL(urlStr);
		   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();
   }
   /*
    * 该函数返回整形:-1 表示下载文件出错  0 表示下载文件成功   1 表示下载文件已经存在
    */
  /* public int downFile(String urlStr,String path,String fileName){
	   InputStream inputStream=null;
	   try{
		   FileUtils fileUtils=new FileUtils();
		   if(fileUtils.isFileExist(path+fileName)){
			   return 1;
		   }else{
			   inputStream=getInputStreamFromUrl(urlStr);
			   File resultFile=fileUtils.write2SDFromInput(path, fileName, inputStream);
		       if(resultFile==null){
		    	   return -1;
		       }
		   }
	   }catch(Exception e){
		   e.printStackTrace();
		   return -1;
	   }finally{
		   try {
			inputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	   }
	   return 0;
   }
   
   public InputStream getInputStreamFromUrl(String urlStr) throws IOException{
	   url=new URL(urlStr);
	   HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
	   InputStream inputStream=urlConn.getInputStream();
	   return inputStream;
   }*/
}

       (2)、解析文件需要的代码:

View Code
 1 package com.pisces.xml;
2
3
4 import java.util.List;
5
6 import org.xml.sax.Attributes;
7 import org.xml.sax.SAXException;
8 import org.xml.sax.helpers.DefaultHandler;
9
10 import com.pisces.model.Mp3Info;
11
12 public class Mp3ListContentHandler extends DefaultHandler{
13
14 private List<Mp3Info> infos=null;
15 private Mp3Info mp3Info=null;
16 private String tagName=null;
17 @Override
18 public void characters(char[] ch, int start, int length)
19 throws SAXException {
20 String temp=new String(ch,start,length);
21 if(tagName.equals("id")){
22 mp3Info.setId(temp);
23 }else if(tagName.equals("mp3.name")){
24 mp3Info.setMp3Name(temp);
25 }else if(tagName.equals("mp3.size")){
26 mp3Info.setMp3Size(temp);
27 }else if(tagName.equals("lrc.name")){
28 mp3Info.setLrcName(temp);
29 }else if(tagName.equals("lrc.size")){
30 mp3Info.setLrcSize(temp);
31 }
32
33 }
34
35 @Override
36 public void endDocument() throws SAXException {
37 // TODO Auto-generated method stub
38 super.endDocument();
39 }
40
41 @Override
42 public void endElement(String uri, String localName, String qName)
43 throws SAXException {
44 if(localName.equals("resource")){ //此部分应注意
45 System.out.println("-----------");
46 infos.add(mp3Info);
47 }
48 tagName="";
49 }
50
51 public Mp3ListContentHandler(List<Mp3Info> infos) {
52 super();
53 this.infos = infos;
54 }
55
56 public List<Mp3Info> getInfos() {
57 return infos;
58 }
59
60 public void setInfos(List<Mp3Info> infos) {
61 this.infos = infos;
62 }
63
64 @Override
65 public void startDocument() throws SAXException {
66 // TODO Auto-generated method stub
67 super.startDocument();
68 }
69
70 @Override
71 public void startElement(String uri, String localName, String qName,
72 Attributes attributes) throws SAXException {
73 // TODO Auto-generated method stub
74 this.tagName=localName;
75 if(tagName.equals("resource")){
76 mp3Info=new Mp3Info();
77 }
78 }
79
80 }

        (3)、主代码:

View Code
  1 package com.piseces.mp3player;
2
3 import java.io.StringReader;
4 import java.net.URL;
5 import java.util.ArrayList;
6 import java.util.HashMap;
7 import java.util.Iterator;
8 import java.util.List;
9
10 import javax.xml.parsers.SAXParser;
11 import javax.xml.parsers.SAXParserFactory;
12
13 import org.xml.sax.InputSource;
14 import org.xml.sax.XMLReader;
15
16 import com.pisces.model.Mp3Info;
17 import com.pisces.xml.Mp3ListContentHandler;
18 import com.pisecs.download.HttpDownloader;
19
20 import android.app.Activity;
21 import android.app.ListActivity;
22 import android.os.Bundle;
23 import android.view.Menu;
24 import android.view.MenuItem;
25 import android.widget.SimpleAdapter;
26
27 public class Mp3ListActivity extends ListActivity {
28 private static final int MENU_UPDATE=1;
29 private static final int MENU_ABOUT=2;
30 /** Called when the activity is first created. */
31 public void onCreate(Bundle savedInstanceState) {
32 super.onCreate(savedInstanceState);
33 setContentView(R.layout.main);
34 updateListView();
35
36 }
37
38 @Override
39 public boolean onCreateOptionsMenu(Menu menu) {
40 // TODO Auto-generated method stub
41 menu.add(0, MENU_UPDATE, 1, R.string.mp3list_update);
42 menu.add(0, MENU_ABOUT, 2, R.string.mp3list_about);
43 return super.onCreateOptionsMenu(menu);
44 }
45
46 @Override
47 public boolean onOptionsItemSelected(MenuItem item) {
48 if(item.getItemId()==MENU_UPDATE){
49 //更新按钮
50 updateListView();
51
52 }else if(item.getItemId()==MENU_ABOUT){
53 //关于按钮
54
55 }
56
57 return super.onOptionsItemSelected(item);
58 }
59 public SimpleAdapter buildSimpleAdapter(List<Mp3Info> mp3Infos){
60
61 List<HashMap<String,String>> list=new ArrayList<HashMap<String,String>>();
62 for (Iterator iter=mp3Infos.iterator();iter.hasNext();) {
63 Mp3Info mp3Info=(Mp3Info)iter.next();
64
65 HashMap<String,String> map=new HashMap<String,String>();
66 map.put("mp3_name", mp3Info.getMp3Name());
67 map.put("mp3_size", mp3Info.getMp3Size());
68 list.add(map);
69 }
70 SimpleAdapter simpleAdapter=new SimpleAdapter(Mp3ListActivity.this, list, R.layout.mp3_info_item,
71 new String[]{"mp3_name","mp3_size"},
72 new int[]{R.id.mp3_name,R.id.mp3_size});
73 return simpleAdapter;
74 }
75 //列表更新按钮方法
76 public void updateListView(){
77 String xml=downloadXML("http://192.168.2.101:8080/mp3/resources.xml");
78 System.out.println("xml--->"+xml);
79 List<Mp3Info> mp3Infos=parseSAX(xml);
80 SimpleAdapter SA=buildSimpleAdapter(mp3Infos);
81 setListAdapter(SA );
82
83 }
84
85 public String downloadXML(String urlStr){
86 HttpDownloader httpDownloader=new HttpDownloader();
87 String xmlStr=httpDownloader.download(urlStr);
88 return xmlStr;
89 }
90
91 //SAX解析过程
92 public List<Mp3Info> parseSAX(String xmlStr){
93 SAXParserFactory factory=SAXParserFactory.newInstance();
94 SAXParser parser;
95 List<Mp3Info> infos=new ArrayList<Mp3Info>();
96 try {
97 parser = factory.newSAXParser();
98 XMLReader xmlreader=parser.getXMLReader();
99 Mp3ListContentHandler mp3listContentHandler=new Mp3ListContentHandler(infos);
100 xmlreader.setContentHandler(mp3listContentHandler);
101 xmlreader.parse(new InputSource(new StringReader(xmlStr)));
102
103 for(Iterator iterator=infos.iterator();iterator.hasNext();){
104 System.out.println("*************");
105 Mp3Info mp3Info=(Mp3Info)iterator.next();
106 System.out.println(mp3Info);
107 }
108
109
110
111 } catch (Exception e) {
112 e.printStackTrace();
113 }
114
115 return infos;
116 }
117 }

        (4)、数据部分代码:

View Code
 1 package com.pisces.model;
2
3 public class Mp3Info {
4 private String id;
5 private String mp3Name;
6 private String mp3Size;
7 private String lrcName;
8 private String lrcSize;
9 public Mp3Info() {
10 super();
11 }
12 public Mp3Info(String id, String mp3Name, String mp3Size, String lrcName,
13 String lrcSize) {
14 super();
15 this.id = id;
16 this.mp3Name = mp3Name;
17 this.mp3Size = mp3Size;
18 this.lrcName = lrcName;
19 this.lrcSize = lrcSize;
20 }
21
22 public String getId() {
23 return id;
24 }
25 @Override
26 public String toString() {
27 return "Mp3Info [id=" + id + ", lrcName=" + lrcName + ", lrcSize="
28 + lrcSize + ", mp3Name=" + mp3Name + ", mp3Size=" + mp3Size + "]";
29 }
30 public void setId(String id) {
31 this.id = id;
32 }
33 public String getMp3Name() {
34 return mp3Name;
35 }
36 public void setMp3Name(String mp3Name) {
37 this.mp3Name = mp3Name;
38 }
39 public String getMp3Size() {
40 return mp3Size;
41 }
42 public void setMp3Size(String mp3Size) {
43 this.mp3Size = mp3Size;
44 }
45 public String getLrcName() {
46 return lrcName;
47 }
48 public void setLrcName(String lrcName) {
49 this.lrcName = lrcName;
50 }
51 public String getLrcSize() {
52 return lrcSize;
53 }
54 public void setLrcSize(String lrcSize) {
55 this.lrcSize = lrcSize;
56 }
57 }

4、为应用程序添加相应的权限:

   <uses-permission android:name="android.permission.INTERNET"/>

 5、项目结构如下:

  

  6、程序运行效果:

   

说明:此部分内容是根据视频教程写出来的,还有很多功能没有完善,通过这部分内容可以从中学会文件的下载与解析的知识!

       在运行此程序时,记得先启动tomcat服务器!

补充:在这个程序中用到了文件下载知识,文件下载的关键代码如下:(说明:补充内容与上面程序没有直接关联)

FileUtils.java:

View Code
 1 package com.utils;
2
3 import java.io.File;
4 import java.io.FileNotFoundException;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.OutputStream;
9
10 import android.os.Environment;
11
12 public class FileUtils {
13 private String SDPATH;
14
15 public String getSDPATH(){
16 return SDPATH;
17 }
18 public FileUtils(){
19 //得到当前外部存储设备的目录
20 SDPATH=Environment.getExternalStorageDirectory()+"/";
21 }
22
23 /*
24 * 在SD卡上创建文件
25 */
26 public File creatSDFile(String fileName){
27 File file=new File(SDPATH+fileName);
28 try {
29 file.createNewFile();
30 } catch (IOException e) {
31 // TODO Auto-generated catch block
32 e.printStackTrace();
33 }
34 return file;
35 }
36 /*
37 * 在SD卡上创建目录
38 */
39 public File creatSDDir(String dirName){
40 File dir=new File(SDPATH+dirName);
41 dir.mkdir();
42 return dir;
43 }
44
45 /*
46 * 判断SD卡上的文件夹是否存在
47 */
48 public boolean isFileExist(String fileName){
49 File file=new File(SDPATH+fileName);
50 return file.exists();
51 }
52
53 /*
54 * 将一个InputStream 里面的数据写入到SD卡中
55 */
56 public File write2SDFromInput(String path,String fileName,InputStream input){
57 File file=null;
58 OutputStream output=null;
59 creatSDDir(path);
60 file=creatSDFile(path+fileName);
61 try {
62 output=new FileOutputStream(file);
63 byte buffer[]=new byte[4*1024];
64 while((input.read(buffer))!=-1){
65 output.write(buffer);
66 }
67 output.flush();
68 } catch (Exception e) {
69 // TODO Auto-generated catch block
70 e.printStackTrace();
71 }finally{
72 try {
73 output.close();
74 } catch (IOException e) {
75 // TODO Auto-generated catch block
76 e.printStackTrace();
77 }
78 }
79
80 return file;
81 }
82 }

HttpDownLoader.java:

View Code
 1 package com.utils;
2
3 import java.io.BufferedReader;
4 import java.io.File;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.InputStreamReader;
8 import java.net.HttpURLConnection;
9 import java.net.URL;
10
11 public class HttpDownLoader {
12 private URL url=null;
13
14 public String download(String urlStr){
15 StringBuffer sb=new StringBuffer();
16 String line=null;
17 BufferedReader buffer=null;
18 try{
19 url=new URL(urlStr);
20 HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
21 buffer=new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
22 while((line=buffer.readLine())!=null){
23 sb.append(line);
24 }
25 }catch(Exception e){
26 e.printStackTrace();
27 }finally{
28 try{
29 buffer.close();
30 }catch(Exception e){
31 e.printStackTrace();
32 }
33 }
34 return sb.toString();
35 }
36 /*
37 * 该函数返回整形:-1 表示下载文件出错 0 表示下载文件成功 1 表示下载文件已经存在
38 */
39 public int downFile(String urlStr,String path,String fileName){
40 InputStream inputStream=null;
41 try{
42 FileUtils fileUtils=new FileUtils();
43 if(fileUtils.isFileExist(path+fileName)){
44 return 1;
45 }else{
46 inputStream=getInputStreamFromUrl(urlStr);
47 File resultFile=fileUtils.write2SDFromInput(path, fileName, inputStream);
48 if(resultFile==null){
49 return -1;
50 }
51 }
52 }catch(Exception e){
53 e.printStackTrace();
54 return -1;
55 }finally{
56 try {
57 inputStream.close();
58 } catch (IOException e) {
59 // TODO Auto-generated catch block
60 e.printStackTrace();
61 }
62 }
63 return 0;
64 }
65
66 public InputStream getInputStreamFromUrl(String urlStr) throws IOException{
67 url=new URL(urlStr);
68 HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
69 InputStream inputStream=urlConn.getInputStream();
70 return inputStream;
71 }
72 }
posted @ 2011-07-18 23:32  月亮的影子  阅读(2024)  评论(2编辑  收藏  举报