0%

Android 下载并保存文件函数

下面的函数可以下载文件,并保存到指定目录。有点简单,只有一个URL的参数,可以自己加上保存目录,以及获取文件类型再生成相应的文件名,这样就完美了。

public void down_file(String url) throws IOException{
        //下载函数   	
        URL myURL = new URL(url);
        URLConnection conn = myURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        if (is == null) throw new RuntimeException("stream is null");
        //把文件存到path
        String path="/sdcard/temp.apk";
        OutputStream os = new FileOutputStream(path);    
        byte buf[] = new byte[1024];  
        do
          {
            int numread = is.read(buf);
            if (is.read(buf) == -1)
            {
              break;
            }
            os.write(buf, 0, numread);           
          } while (true);
       
            is.close();
            os.close();
               
    }