纸上得来终觉浅,绝知此事要躬行。

 

Android下载帮助类

以下两个类配合使用:

HttpURLConnection
package sRoger.pack;

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.util.Log;

public class sRogerHttpDownload {
    private String tag="sRogerHttp";
    private BufferedReader reader=null;
    
    /**
     * 返回一个HttpURLConnection实例
     * @param url URL
     * @return
     * @throws IOException
     */
    private HttpURLConnection GetConnection(String url) throws IOException {
        URL u;
        HttpURLConnection httpCon;
        u = new URL(url);
        httpCon = (HttpURLConnection) u.openConnection();
        return httpCon;
    }
    
    /**
     * 下载函数
     * @return
     */
    public String HttpDownLoader(String url){
        StringBuffer sb=new StringBuffer();
        String line=null;
        try{
            HttpURLConnection con = this.GetConnection(url);
            InputStream iStream=con.getInputStream();
            InputStreamReader is=new InputStreamReader(iStream);
            reader=new BufferedReader(is);
            
            while((line = reader.readLine())!=null){
                sb.append(line+"-");
                Log.d(tag, line);
            }
            Log.d(tag, "下载完成.");
        }
        catch(IOException e){
            Log.d(tag,"下载出错.");
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally{
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
    
    
    /**
     * 返回值:[1:文件已经存在],[-1:下载失败],[0:下载成功]
     * @param strUrl
     * @param path
     * @param fileName
     * @return
     */
    public int DownFile(String strUrl,String path,String fileName){
        InputStream input=null;
        try{
            sRogerFileUtils fUtily=new sRogerFileUtils();
            if(fUtily.IsFileExist(path+fileName)){
                return 1;
            }else{
                input=getInputStreamFromUrl(strUrl);
                if(input==null){
                    return -1;
                }
                File resultFile=fUtily.Write2SDFromInputStream(path, fileName, input);
                if(resultFile==null){
                    return -1;
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
        finally{
            try{
                input.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
        return 0;
    }
    
    /**
     * 根据URL得到输入流
     * @param url
     * @return
     */
    private InputStream getInputStreamFromUrl(String url){
        InputStream inputStream=null;
        try{
            HttpURLConnection urlConn=this.GetConnection(url);
            inputStream=urlConn.getInputStream();
        }
        catch(MalformedURLException e){
            e.printStackTrace();
        }
        catch(IOException e){
            e.printStackTrace();
        }
        return inputStream;
    }
}
WriteToSDCard
package sRoger.pack;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Environment;
import android.util.Log;

public class sRogerFileUtils {
    private String SDPATH;
    private String tag="sRogerHttp";
    /**
     * 构造函数
     */
    public sRogerFileUtils(){
        // 得到当前外储设备的目录
        SDPATH=Environment.getExternalStorageDirectory()+"/";
        Log.d(tag, SDPATH);
    }

    /**
     * 获取SD卡路径
     * @return
     */
    public String getSDPATH() {
        return SDPATH;
    }
    
    /**
     * 在SD卡上创建文件
     * @param fileName  文件名称
     * @return
     * @throws IOException
     */
    public File CreateSDFile(String fileName) throws IOException{
        File file=new File(SDPATH + fileName);
        file.createNewFile();
        return file;
    }
    
    /**
     * 在SD卡上创建目录
     * @param dirName  目录名称
     * @return
     * @throws IOException
     */
    public File CreateSDDir(String dirName) throws IOException{
        File dir=new File(SDPATH+dirName);
        dir.mkdir();
        return dir;
    }
    
    /**
     * 判断指定文件是否存在
     * @param fileName  文件名称
     * @return
     */
    public boolean IsFileExist(String fileName){
        File file=new File(SDPATH + fileName);
        return file.exists();
    }
    
    /**
     * 将文件写入到SD卡
     * @param path  路径
     * @param fileName  文件名称
     * @param stream  读到了流
     * @return
     */
    public File Write2SDFromInputStream(String path,String fileName,InputStream stream){
        File file = null;
        OutputStream ostream=null;
        try{
            this.CreateSDDir(path);
            file = this.CreateSDFile(fileName);
            ostream = new FileOutputStream(file);
            byte[] buffer=new byte[4*1024];
            while((stream.read(buffer))!=-1){
                ostream.write(buffer);
            }
            ostream.flush();
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally{
            try{
                ostream.close();
            }
            catch(Exception ex){
                ex.printStackTrace();
            }
        }
        return file;
    }
}

调用方法:

调用
// 请求连接
        btnConn=(Button)findViewById(R.id.button1);
        btnConn.setOnClickListener(new OnClickListener() {
            
            public void onClick(View v) {
                sRogerHttpDownload srh=new sRogerHttpDownload();
                String result=srh.HttpDownLoader("http://192.168.3.51:91/%E4%B8%8D%E7%AE%A1%E6%9C%89%E5%A4%9A%E8%8B%A6.lrc");
                Log.d(tag, result.substring(0,result.length()-1));
            }
        });
        
        // 下载文件到SD卡
        btnDown=(Button)findViewById(R.id.button2);
        btnDown.setOnClickListener(new OnClickListener() {
            
            public void onClick(View v) {
                sRogerHttpDownload http=new sRogerHttpDownload();
                //http://192.168.3.51:91/%E6%8B%A5%E6%8A%B1%E7%9A%84%E9%97%AE%E5%8F%B7.mp3
                int resultInt = http.DownFile("http://192.168.3.51:91/%E4%B8%8D%E7%AE%A1%E6%9C%89%E5%A4%9A%E8%8B%A6.lrc", "/", "sjr.lrc");
                Log.d(tag, resultInt+"");
            }
        });

注意:

  要使用Android访问网络或向外部设置写入数据,必须在AndroidManifest.xml中做如下的配置:

  

<!-- 要想访问网络和文件必须设置下面两个配置项 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

这两个配置信息写在</manifest>之上即可。

posted on 2012-06-14 19:25  JRoger  阅读(328)  评论(0编辑  收藏  举报

导航