下载文件

    技术2022-05-20  88

    1.下载工具类,将要下载的文件保存到SD卡中

     

    package com.huo;

    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 DownloadUtils {  private String SDPATH;   public String getSDPATH() {  return SDPATH; }

     

     

     

    /* 获取外部存储设备目录*/  public DownloadUtils() {   /*Environment.getExternalStorageState()方法用于获取SDCard的状态,       *如果手机装  有SDCard,并且可以进行读写,那么方法返回的状态等于Environment.MEDIA_MOUNTED*/    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){   /*获取SD卡的存储路径*/     SDPATH = Environment.getExternalStorageDirectory() + "/";  

       } } 

     

     

     /*在SD卡上创建文件*/ public File createSDFile(String filename) throws IOException{  File file = new File(SDPATH + filename);  file.createNewFile();  return file;   }  /*创建SD卡目录*/ public File createSDir(String dirname){  File dir = new File(SDPATH + dirname);  dir.mkdir();  return dir; }  /*判断SD卡上文件是否存在*/ public boolean isFileExist(String filename){  File file = new File(SDPATH + filename);  return file.exists(); }  /*从输入流中读出数据写入到SD卡中,从输入流中读取数据,保存到字节数组中,然后将数据写入到输出流中  * @param dirname 存储路径  * @param filename 文件名  * @param is 输入流  * */  public File write2SDFromInput(String path,String filename,InputStream is){             File file = null;             OutputStream os = null;             try {                 createSDir(path);                 file = createSDFile(path + filename);               /*创建一个向指定 File 对象表示的文件中写入数据的文件输出流*/              os = new FileOutputStream(file);                 byte[] buffer = new byte[4*1024];                 while((is.read(buffer)) != -1){                  os.write(buffer);                 }                 os.flush();             }              catch (Exception e) {                 e.printStackTrace();             }             finally{                 try {                  os.close();                 } catch (IOException e) {                     e.printStackTrace();                 }             }             return file;         }    

    }

     

    ===========================================

     

    2.实现文件下载

     

    package com.huo;

    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 Downloader {  private URL url = null;  public String downloadTXTFile(String httpUrl){  BufferedReader buffer = null;  StringBuffer sb = new StringBuffer();  String line = null;     /*获取URL对象*/   try {    url = new URL(httpUrl);    /*获取HttpURLConnection对象*/    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();        /*创建BufferedReader,用来读取数据*/    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 (IOException e) {     // TODO Auto-generated catch block     e.printStackTrace();    }   }      return sb.toString(); } 

      /*  * 下载文件  * 0代表下载成功  * 1代表该文件以存在        * -1代表下载失败        * */

     public int downloadFile(String urlStr,String path,String filename){    InputStream is = null;    try{   DownloadUtils downloadUtils = new DownloadUtils();   /*判断该文件是否存在*/   if(downloadUtils.isFileExist(path + filename)){    return 1;   }   else{    is = getInputStreamFromURL(urlStr);    File resultFile = downloadUtils.write2SDFromInput(path, filename, is);    if(resultFile == null){     return -1;    }   }   }catch(Exception e){   e.printStackTrace();   return -1;  }//  finally{//   try {//    is.close();//   } catch (IOException e) {//    e.printStackTrace();//   }//  }    return 0; }  /*根据URL,取得输入流*/ public InputStream getInputStreamFromURL(String urlStr){    InputStream is = null;  try {   url = new URL(urlStr);   HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();   is = httpConn.getInputStream();    } catch (Exception e) {   e.printStackTrace();  }  return is; }}

    =============================================

     

    3.Activity

     

    package com.huo;

    import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;

    public class DownloadActivity extends Activity {  Button button01; Button button02; Downloader downloader = null;    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        button01 = (Button) findViewById(R.id.Button01);        button01.setOnClickListener(new View.OnClickListener() {      @Override   public void onClick(View v) {    downloader = new Downloader();    String str = downloader.downloadTXTFile("http://10.0.2.2:8080/oa/aaa.txt");    System.out.println(str);   }  });                button02 = (Button) findViewById(R.id.Button02);        button02.setOnClickListener(new View.OnClickListener() {      @Override   public void onClick(View v) {    downloader = new Downloader();    int result = downloader.downloadFile("http://10.0.2.2:8080/oa/aaa.txt",            "voa/","aaa.txt");    System.out.println(result);   }  });    }        }


    最新回复(0)