web文件下载和Android文件下载的区别小结

来源:互联网 发布:淘宝信誉评级极好 编辑:程序博客网 时间:2024/06/14 17:05

web文件下载和Android文件下载的区别

web文件下载

    //得到要下载文件的路径    String path = getServletContext().getRealPath("/down/a.zip");    //得到文件的名称    //得到最后一个\位置,根据位置进行截取    int lens = path.lastIndexOf("\\");    String filename = path.substring(lens+1);    //设置头信息    response.setHeader("Content-Disposition", "attachment;filename="+filename);    //得到文件的输入流    InputStream in = new FileInputStream(path);    //使用输出流操作    OutputStream out = response.getOutputStream();    //流对接    int len = 0;    byte[] b = new byte[8192];    while((len=in.read(b))!=-1) {        out.write(b, 0, len);    }    //关闭流    in.close();

Android文件下载

URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();//告诉服务器 只想下载资源的一部分conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);InputStream is = conn.getInputStream();byte[] buffer = new byte[8192];int len = -1;RandomAccessFile raf = new RandomAccessFile(getFileName(path), "rw");raf.seek(startIndex);//每个线程写文件的开始位置都是不一样的.while((len = is.read(buffer))!=-1){    //把每个线程下载的数据放在自己的空间里面.    raf.write(buffer,0, len);}raf.close();is.close();
0 0
原创粉丝点击