java实现从网络下载多个文件
java从网络下载多个文件,供大家参考,具体内容如下
首先是打包下载多文件,即打成压缩包在下载。
其次别处的资源:可以是别的服务器,可以是网上的资源,当然也可以是本地的(更简单)
最后:一次性下载,一次性下载多个文件
三步走:
一、先将“别处”需要下载的文件下载到服务器,然后将文件的路径改掉
二、然后将服务器上的文件打成压缩包
三、下载这个压缩包
//下载 @RequestMapping("/download01") publicvoiddownloadImage(StringtcLwIds,HttpServletRequestrequest,HttpServletResponseresponse)throwsException{ booleandflag=false; String[]paths=tcLwIds.split(","); File[]file1=newFile[paths.length]; DownLoadImageUtilimageUtils=newDownLoadImageUtil(); if(paths.length>1){ for(inti=0;i0){ out.write(buffer,0,len); } out.closeEntry(); fis.close(); } out.close(); //下载的服务地址根据实际情况修改 booleandflag=downloafile(request,response,"http://localhost:8080/data/"+tmpFileName); //将服务器上压缩前的源文件删除 for(inti=0;i makeImage();方法(如果是服务器上的图片,可以省略这一步,直接打包)
/** *下载图片,并按照指定的路径存储 *@parambean *@paramfilePath */ publicvoidmakeImage(StringfilePath){ //网络请求所需变量 try{ //new一个URL对象 URLurl=newURL(filePath); //打开链接 HttpURLConnectionconn=(HttpURLConnection)url.openConnection(); //设置请求方式为"GET" conn.setRequestMethod("GET"); //超时响应时间为5秒 conn.setConnectTimeout(5*1000); //通过输入流获取图片数据 InputStreaminStream=conn.getInputStream(); ByteArrayOutputStreamoutStream=newByteArrayOutputStream(); //创建一个Buffer字符串 byte[]buffer=newbyte[1024]; //每次读取的字符串长度,如果为-1,代表全部读取完毕 intlen=0; //使用一个输入流从buffer里把数据读取出来 while((len=inStream.read(buffer))!=-1){ //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度 outStream.write(buffer,0,len); } byte[]data=outStream.toByteArray(); //先将图片从url下载到服务器的D:/upload/ FileimageFile=newFile("D:/upload/"+filePath.substring(filePath.lastIndexOf("/"))); //创建输出流 FileOutputStreamfoutStream=newFileOutputStream(imageFile); foutStream.write(data); //关闭输出流 foutStream.close(); inStream.close(); }catch(MalformedURLExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } }以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。