• android下载实例


    1、Androidmanifest.xml的文件一定要加上权限

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="chester.download"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="4" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
    android:label="@string/app_name"
    android:name=".DownLoadexample" >
    <intent-filter >
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    </activity>
    </application>

    </manifest>

    2、activity代码如下:

    package chester.download;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.Toast;
    import chester.utils.HttpDownloader;
    
    /**
     * 
     *@title        DownLoadexample
     *@describe		TODO 使用http协议下载txt文件和mp3文件
     *@author		Chester	
     *@date			2011-11-4
     *@version		V1.0
     */
    public class DownLoadexample extends Activity {
    	
    	private Button downloadtxtButton =null;
    	private Button downloadfilebuButton=null;
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            /**
             * 得到两个button控件对象
             */
            downloadtxtButton=(Button)findViewById(R.id.downloadtxtbutton);
            downloadfilebuButton=(Button)findViewById(R.id.downloadmp3button);
            downloadtxtButton.setOnClickListener(new TxtButtonListener());
            downloadfilebuButton.setOnClickListener(new FileButtonListener());
        }
        
        /**
         * 
         *@title        TxtButtonLinstener
         *@describe		TODO 使用内部类实现TxtButtonLinstener监听器
         *@author		Chester	
         *@date			2011-11-4
         *@version		V1.0
         */
        class TxtButtonListener implements OnClickListener{
    
    		@Override
    		public void onClick(View v) {
    			// TODO Auto-generated method stub
    			//HttpDownloader 是自己写的类,封装起来,以后使用方便
    			HttpDownloader httpDownloader=new HttpDownloader();
    			//根据URL得到文件
    			String str=httpDownloader.downloadfile("http://3g.sina.com.cn/");
    			//得到的是sina的wap包wml语言
    			System.out.println(str);
    			Toast.makeText(DownLoadexample.this, str, Toast.LENGTH_LONG).show();
    		}
        	
        }
        
        /**
         * 
         *@title        FileButtonListener
         *@describe		TODO 使用内部类实现Mp3ButtonLinstener监听器
         *@author		Chester	
         *@date			2011-11-4
         *@version		V1.0
         */
        
        class FileButtonListener implements OnClickListener{
    
    		@Override
    		public void onClick(View v) {
    			// TODO Auto-generated method stub
    			HttpDownloader httpDownloader=new HttpDownloader();
    			int mp3int=httpDownloader.downloadFile("http://u.androidgame-store.com/android1/new/game1/24/110424/kwplayer_1.apk", "mymp3", "chester.apk");
    			Toast.makeText(DownLoadexample.this, mp3int+"/", Toast.LENGTH_SHORT).show();
    		}
        	
        }
    }
    

      


    3、HttpDownloader类的代码

    package chester.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;
    
    /**
     * 
     *@title        HttpDownloader
     *@describe		TODO 根据URL下载文件类
     *					 1、首先创建一个URL对象
     *					 2、根据URL对象,创建一个HttpURLConnection对象
     *					 3、得到IputStream
     *					 4、从IputStream当中读取数据
     *@author		Chester	
     *@date			2011-11-4
     *@version		V1.0
     */
    public class HttpDownloader {
    
    	private URL url=null;
    	
    	/**
    	 * 
    	 *@title 		download
    	 *@describe		TODO 根据url下载文件,前提是这个文件当中的内容是文本,函数返回值是这个文件的文本内容
    	 *@param		@param urlsString
    	 *@param		@return
    	 *@throws
    	 */
    	public String downloadfile(String urlString) {
    		
    		StringBuffer stringBuffer=new StringBuffer();
    		String line=null;
    		BufferedReader bufferedReader=null;
    		try {
    			//创建一个URL对象
    			url=new URL(urlString);
    			//创建一个http连接
    			HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
    			//使用IO流读取数据
    			bufferedReader=new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    			while ((line=bufferedReader.readLine())!=null) {
    				stringBuffer.append(line);
    				
    			}
    		} catch (Exception e) {
    			// TODO: handle exception
    			e.printStackTrace();
    		}finally{
    			//下面还有加上try,有可能关不了
    			try {
    				bufferedReader.close();
    			} catch (Exception e) {
    				// TODO: handle exception
    				e.printStackTrace();
    			}
    			
    		}
    		
    		return stringBuffer.toString();
    	}
    
    	/**
    	 * 
    	 *@title 		downFile
    	 *@describe		TODO 该函数可以下载任意文件。返回-1:代表下载文件出错,0:代表下载文件成功,1:代表文件已经存在
    	 *@param		@param urString 网络地址
    	 *@param		@param path     存放路径
    	 *@param		@param fileName 存放文件名
    	 *@param		@return
    	 *@throws
    	 */
    	public int downloadFile(String urlStr,String path,String fileName) {
    		InputStream inputStream=null;
    		try {
    			FileUtils fileUtils=new FileUtils();
    			//判断文件是否存在,存在则返回1 path+"/"+fileName这个参数一定要写对。
    			if (fileUtils.isFileExist(path+"/"+fileName)) {
    				return 1;
    			}else {
    				//根据URL得到输入流
    				inputStream=getInputStreamFromUrl(urlStr);
    				File resultFile=fileUtils.write2SDFromInput(path, fileName, inputStream);
    				if (resultFile==null) {
    					//文件是空的就返回-1
    					return -1;					
    				}		
    			}
    		} catch (Exception e) {
    			// TODO: handle exception
    			e.printStackTrace();
    		}finally{
    			try {
    				inputStream.close();
    			} catch (Exception e2) {
    				// TODO: handle exception
    				e2.printStackTrace();
    			}
    		}
    		return 0;
    	}
    	
    	/**
    	 * 
    	 *@title 		getInputStreamFromUrl
    	 *@describe		TODO 根据URL得到输入流
    	 *@param		@param urlstr
    	 *@param		@return
    	 *@param		@throws MalformedURLException
    	 *@param		@throws IOException
    	 *@throws
    	 */
    	public InputStream getInputStreamFromUrl(String urlstr) throws MalformedURLException,IOException{
    		url=new URL(urlstr);
    		HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
    		InputStream inputStream=httpURLConnection.getInputStream();
    		return inputStream;
    	
    		
    	}
    	
    }
    

    4、FileUtils代码

    package chester.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;
    
    /**
     * 
     *@title        FileUtils
     *@describe		TODO
     *@author		Chester	
     *@date			2011-11-4
     *@version		V1.0
     */
    public class FileUtils {
    
    	//路径
    	private String SDPATH;
    	/**
    	 * 
    	 *@title 		getSDPATH
    	 *@describe		TODO
    	 *@param		@return
    	 *@throws
    	 */
    	public String getSDPATH() {
    		return SDPATH;
    	}
    	
    	/**
    	 * 
    	 *@Title
    	 *@describe		TODO 构造函数,得到SD当前目录
    	 *@param
    	 */
    	public FileUtils(){
    		//得到当前外部存储设备的目录
    		// /SDCARD
    		SDPATH=Environment.getExternalStorageDirectory()+"/";		
    	}
    
    	/**
    	 * 
    	 *@title 		createSDFile
    	 *@describe		TODO 在SD卡中创建文件
    	 *@param		@param fileName
    	 *@param		@return
    	 *@param		@throws IOException
    	 *@throws
    	 */
    	public File createSDFile(String fileName) throws IOException{
    		File file = new File(SDPATH + fileName);
    		file.createNewFile();
    		return file;
    		
    	}
    	
    	/**
    	 * 
    	 *@title 		createSDDir
    	 *@describe		TODO 在SD卡上创建目录
    	 *@param		@param fileName
    	 *@param		@return
    	 *@throws
    	 */
    	public File createSDDir(String fileName) {
    		File dir =new File(SDPATH+fileName);
    		dir.mkdir();
    		return dir;
    	}
    	
    	/**
    	 * 
    	 *@title 		isFileExist
    	 *@describe		TODO 判定SD卡中的文件夹是否存在
    	 *@param		@param fileName
    	 *@param		@return
    	 *@throws
    	 */
    	public boolean isFileExist(String fileName) {
    		File file = new File(SDPATH + fileName);
    		return file.exists();
    	}
    	
    	/**
    	 * 
    	 *@title 		write2SDFromInput
    	 *@describe		TODO 将一个inputstream的数据写入到SD卡中
    	 *@param		@param path
    	 *@param		@param fileName
    	 *@param		@param inputStream
    	 *@param		@return
    	 *@throws
    	 */
    	public File write2SDFromInput(String path,String fileName,InputStream inputStream) {
    		File file=null;
    		OutputStream outputStream=null;
    		
    		try {
    			//创建文件夹
    			createSDDir(path);
    		   //在path文件夹下创建文件,+"/"这个必须加
    			file=createSDFile(path+"/"+fileName);
    			outputStream=new FileOutputStream(file);
    			//每一个以4K的速度写入
    			byte buffer[]=new byte[4*1024];
    			while ((inputStream.read(buffer))!=-1) {
    				outputStream.write(buffer);
    			}
    			//清空一下缓存
    			outputStream.flush();
    		} catch (Exception e) {
    			// TODO: handle exception
    			e.printStackTrace();
    		}finally{
    			try {
    				//把打开的流关闭掉
    				outputStream.close();
    			} catch (Exception e2) {
    				// TODO: handle exception
    				e2.printStackTrace();
    			}
    			
    		}
    		
    		return file;
    		
    	}
    	
    }
    

      

      

      


  • 相关阅读:
    如何使用Arrays工具类操作数组
    Java 内存模型详解
    HashSet源码分析:JDK源码系列
    在ASP.NET Core中用HttpClient(六)——ASP.NET Core中使用HttpClientFactory
    在ASP.NET Core中用HttpClient(五)——通过CancellationToken取消HTTP请求
    在ASP.NET Core中用HttpClient(四)——提高性能和优化内存
    ASP.NET Core与Redis搭建一个简易分布式缓存
    在ASP.NET Core中用HttpClient(三)——发送HTTP PATCH请求
    在ASP.NET Core中用HttpClient(二)——发送POST, PUT和DELETE请求
    在ASP.NET Core中用HttpClient(一)——获取数据和内容
  • 原文地址:https://www.cnblogs.com/chester/p/2236563.html
Copyright © 2020-2023  润新知