android通过网络下载文字和Mp3的例子

android通过网络下载文件分2步:

1.建立网络连接获取数据流;

2.创建文件把数据流写到文件中即可。(简单吧)

废话不多说,上代码:

网络处理类 HttpDownloader.java

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;

/***
 * 通过http协议下载文件
 * ***/
public class HttpDownloader {
  
    private URL url = null;欠款
   
    public InputStream getInputStreamFormUrl(String urlStr)
            throws MalformedURLException,IOException{
        url = new URL(urlStr);
        HttpURLConnection httpc = (HttpURLConnection)url.openConnection();
        return httpc.getInputStream();
    }

    public String downloadText(String urlStr){
         StringBuffer sb = new StringBuffer();
         String line = null;
         BufferedReader breader = null;
         try{
             url = new URL(urlStr);
             HttpURLConnection httpc = (HttpURLConnection)url.openConnection();
             InputStream inputs = httpc.getInputStream();
             breader = new BufferedReader(new InputStreamReader(inputs));
             while((line=breader.readLine())!=null){
                 sb.append(line);
             }             
         }catch(Exception e){
             e.printStackTrace();
         }finally{
             try {
                breader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
         } 
         return sb.toString();
    }
   
    public int downloadFile(String urlStr,String path,String name){
        InputStream input = null;
        try{
            FileUtils fu = new FileUtils();
            if(fu.isFileExist(path+name)){   // 是否存在文件,如果存在返回1
               return 1;
            }else{
                input = getInputStreamFormUrl(urlStr);
                File f = fu.inputStream2File(path, name, input);软件开发
                if(f==null){
                    return -1;              // 数据有异常的时候返回-1
                }
                    input.close();
            }
        }catch(Exception e){
          e.printStackTrace();   
          return -1;
        }
        return 0;                         // 数据正常的时候返回0
    }
   
}

原文地址:https://www.cnblogs.com/sky7034/p/2152805.html