欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android实现文件下载功能

程序员文章站 2023-12-29 08:03:22
android 在网络上下载文件,供大家参考,具体内容如下 步骤 : 1.使用http协议下载文件 - 创建一个httpurlconnection对象...

android 在网络上下载文件,供大家参考,具体内容如下

步骤 :

1.使用http协议下载文件

- 创建一个httpurlconnection对象 : httpurlconnection urlconn = (httpurlconnection) url.openconnection();
- 获取一个inputstream对象 : urlconn.getinputstream()
- 访问网络的权限 : android.permission.internet

2.将下载的文件写入sdcard
- 得到当前设备sd卡的目录 : environment.getexternalstragedirectory()
- 访问sd卡的权限 : android.permission.write_external_storage

代码 : 

activity_main.xml

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" 
  xmlns:tools="http://schemas.android.com/tools" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  android:paddingbottom="@dimen/activity_vertical_margin" 
  android:paddingleft="@dimen/activity_horizontal_margin" 
  android:paddingright="@dimen/activity_horizontal_margin" 
  android:paddingtop="@dimen/activity_vertical_margin" 
  tools:context=".mainactivity" > 
 
  <button 
    android:id="@+id/btn_txt" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="download lrc" /> 
   
  <button 
    android:id="@+id/btn_mp3" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_below="@id/btn_txt" 
    android:text="download mp3" /> 
 
</relativelayout> 

mainactivity.java

package com.chay.download; 
 
import com.chay.utils.httpdownloader; 
 
import android.app.activity; 
import android.os.bundle; 
import android.view.view; 
import android.view.view.onclicklistener; 
import android.widget.button; 
 
public class mainactivity extends activity { 
   
  string urlstr_txt = "http://192.168.56.1:8080/mp3/wan.lrc"; 
  string urlstr_mp3 = "http://192.168.56.1:8080/mp3/wan.mp3"; 
  string path = "mp3/"; 
  string filename = "wan.mp3"; 
  private button downloadtxtbutton; 
  private button downloadmp3button; 
 
  @override 
  protected void oncreate(bundle savedinstancestate) { 
    super.oncreate(savedinstancestate); 
    setcontentview(r.layout.activity_main); 
    downloadtxtbutton = (button) findviewbyid(r.id.btn_txt); 
    downloadtxtbutton.setonclicklistener(new downloadtxtlistener()); 
    downloadmp3button = (button) findviewbyid(r.id.btn_mp3); 
    downloadmp3button.setonclicklistener(new downloadmp3listener()); 
  } 
 
  //下载歌词文件按钮监听器 
  class downloadtxtlistener implements onclicklistener { 
    @override 
    public void onclick(view v) { 
      thread t = new downloadtxtthread();  
      t.start(); 
      system.out.println("txt--->"); 
    } 
  } 
  //下载歌词文件线程 
  class downloadtxtthread extends thread{ 
    @override 
    public void run() { 
      httpdownloader httpdownloader = new httpdownloader(); 
      string lrc = httpdownloader.download(urlstr_txt); 
      system.out.println(lrc); 
    } 
  } 
  //下载mp3文件按钮监听器 
  class downloadmp3listener implements onclicklistener { 
    @override 
    public void onclick(view v) { 
      thread h = new downmp3thread(); 
      h.start(); 
      system.out.println("mp3--->"); 
    } 
  } 
  //下载mp3文件线程 
  class downmp3thread extends thread{ 
    @override 
    public void run() { 
      httpdownloader httpdownloader = new httpdownloader(); 
      int result = httpdownloader.downfile(urlstr_mp3, path, filename); 
      system.out.println(result); 
    } 
  }   
} 

工具类:

httpdownloader.java

package com.chay.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; 
 
public class httpdownloader { 
  private url url = null; 
 
  /** 
   * 根据url下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文件当中的内容 
   * 1.创建一个url对象 
   * 2.通过url对象,创建一个httpurlconnection对象 
   * 3.得到inputstram 
   * 4.从inputstream当中读取数据 
   * @param urlstr 
   * @return 
   */ 
  public string download(string urlstr) { 
    stringbuffer sb = new stringbuffer(); 
    string line = null; 
    bufferedreader buffer = null; 
    try { 
      // 创建一个url对象 
      url = new url(urlstr); 
      // 创建一个http连接 
      httpurlconnection urlconn = (httpurlconnection) url.openconnection(); 
      // 使用io流读取数据 
      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 (exception e) { 
        e.printstacktrace(); 
      } 
    } 
    return 0; 
  } 
 
  /** 
   * 根据url得到输入流 
   * 
   * @param urlstr 
   * @return 
   * @throws malformedurlexception 
   * @throws ioexception 
   */ 
  public inputstream getinputstreamfromurl(string urlstr) 
      throws malformedurlexception, ioexception { 
    url = new url(urlstr); 
    httpurlconnection urlconn = (httpurlconnection) url.openconnection(); 
    inputstream inputstream = urlconn.getinputstream(); 
    return inputstream; 
  } 
} 

fileutils.java

package com.chay.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() { 
    //得到当前外部存储设备的目录 
    // /sdcard 
    sdpath = environment.getexternalstoragedirectory() + "/"; 
  } 
  /** 
   * 在sd卡上创建文件 
   * 
   * @throws ioexception 
   */ 
  public file creatsdfile(string filename) throws ioexception { 
    file file = new file(sdpath + filename); 
    file.createnewfile(); 
    return file; 
  } 
   
  /** 
   * 在sd卡上创建目录 
   * 
   * @param dirname 
   */ 
  public file creatsddir(string dirname) { 
    file dir = new file(sdpath + dirname); 
    dir.mkdirs(); 
    return dir; 
  } 
 
  /** 
   * 判断sd卡上的文件夹是否存在 
   */ 
  public boolean isfileexist(string filename){ 
    file file = new file(sdpath + filename); 
    return file.exists(); 
  } 
   
  /** 
   * 将一个inputstream里面的数据写入到sd卡中 
   */ 
  public file write2sdfrominput(string path,string filename,inputstream input){ 
    file file = null; 
    outputstream output = null; 
    try{ 
      creatsddir(path); 
      file = creatsdfile(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; 
  } 
} 

android实现文件下载功能

 如果不能下载,请先将windows防火墙关闭。

上一篇:

下一篇: