文件管理 · 2024年3月16日

java从httpurl下载文件的方法|Java获取下载文件的大小

A. 用java下载HTTP文件时遇到问题

importjava.net.*;importjava.io.*;publicclassURLConnectionDemo{publicstaticvoidmain(String[]args)throwsException{URLurl=newURL("http://www.scp.e.cn/pantoschoolzz/BG/Bord/Message/DownloadMessageAttachment.aspx?ID=215");URLConnectionuc=url.openConnection();StringfileName=uc.getHeaderField(6);fileName=URLDecoder.decode(fileName.substring(fileName.indexOf("filename=")+9),"UTF-8");System.out.println("文件名为:"+fileName);System.out.println("文件大小:"+(uc.getContentLength()/1024)+"KB");Stringpath="D:"+File.separator+fileName;FileOutputStreamos=newFileOutputStream(path);InputStreamis=uc.getInputStream();byte[]b=newbyte[1024];intlen=0;while((len=is.read(b))!=-1){os.write(b,0,len);}os.close();is.close();System.out.println("下载成功,文件保存在:"+path);}}

//给你一个下载的例子吧,仅供参考。

B. java如何实现超链接下载

java实现超链接下载方法如下:

response.setHeader("Content-disposition","attachment;filename="下载的文件名字);

备注:让response调用setheader方法添加下载的头给客户的浏览器,浏览器收到该头后就会打开相应的下载对话框。

C. java程序下载pdf文件

主要是 URL 和 HttpURLConnection 类的运用,看代码:

importjava.io.DataInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.net.HttpURLConnection;importjava.net.URL;publicclassHttpDownloader{_FILE_URL="http://211.103.156.163/u/cms/www/201511/25051940i6ou.pdf";privatestaticfinalStringLOCAL_FILE_PATH="D:/some.pdf";//改成你保存文件的路径publicstaticvoidmain(String[]args){(REMOTE_FILE_URL,LOCAL_FILE_PATH).download();}privateStringremoteFileUrl;privateStringlocalFilePath;publicHttpDownloader(StringremoteFileUrl,StringlocalFilePath){this.remoteFileUrl=remoteFileUrl;this.localFilePath=localFilePath;}publicvoiddownload(){try{URLurl=newURL(remoteFileUrl);=(HttpURLConnection)url.openConnection();httpURLConnection.setConnectTimeout(5*1000);//5000毫秒内没有连接上则放弃连接httpURLConnection.connect();//连接System.out.println("连接URL成功~");intfileLenght=httpURLConnection.getContentLength();System.out.println("文件大小:"+(fileLenght/1024.0)+"KB");System.out.println("开始下载…");try(DataInputStreamdis=newDataInputStream(httpURLConnection.getInputStream());FileOutputStreamfos=newFileOutputStream(localFilePath)){byte[]buf=newbyte[10240];//根据实际情况可以增大buf大小for(intreadSize;(readSize=dis.read(buf))>0;){fos.write(buf,0,readSize);}System.out.println("下载完毕~");}catch(IOExceptionex){System.out.println("下载时出错");}httpURLConnection.disconnect();}catch(IOExceptionex){System.out.println("URL不存在或者连接超时");}}}

D. java怎样读取http文件服务器上的文件列表并下载

要求文件名不能写死,那么只能到服务器上去遍历目录,如果服务器开了ftp权限的话到可以用apache的commons-net包,里面有ftp功能可以上传下载文件,也可以遍历文件

E. 如何用java语言直接从web上下载数据,从而省去在网页上手动点击下载

URL url = new URL("http://219.219.114.10/infobin/select.dll");URLConnection uc = url.openConnection(); InputStreamReader is = new InputStreamReader(uc.getInputStream()); int line; StringBuffer sb = new StringBuffer(""); while((line=is.read())!=-1){ sb.append((char)line); } String str = sb.toString();//解析其中的内容//可以通过 找到有用的地址文件,然后利用如下url = new URL(“有用的文件路径”);BufferedInputStream in = new BufferedInputStream(url.openStream());哈哈,得到它了,一切就ok啦下面的会了吗,流操作,写到本地

F. java 如何下载文件

httpURLConnection conn;conn.getInputStream;再将这个stream 写到文件就可以了

G. Java获取下载文件的大小

可以直接通过HttpURLConnection 的getContentLength()方法来获取下载文件的大小。//找到要下载的文件 url=new URL( "http://www..com/uploadfile/oracle.txt"); //根据响版应获取文件大权小 HttpURLConnection urlcon=(HttpURLConnection)url.openConnection(); //获取相应的文件长度 fileLength=urlcon.getContentLength();备注:以上方法中url变换即可,下面的方法不用变更,即可获取到对应下载文件的大小。

H. Java 下载文件的方法怎么写

参考下面public HttpServletResponse download(String path, HttpServletResponse response) {try {// path是指欲下载的文件的路径。File file = new File(path);// 取得文件名。String filename = file.getName();// 取得文件的后缀名。String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();// 以流的形式下载文件。InputStream fis = new BufferedInputStream(new FileInputStream(path));byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();// 清空responseresponse.reset();// 设置response的Headerresponse.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));response.addHeader("Content-Length", "" + file.length());OutputStream toClient = new BufferedOutputStream(response.getOutputStream());response.setContentType("application/octet-stream");toClient.write(buffer);toClient.flush();toClient.close();} catch (IOException ex) {ex.printStackTrace();}return response;}// 下载本地文件public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {String fileName = "Operator.doc".toString(); // 文件的默认保存名// 读到流中InputStream inStream = new FileInputStream("c:/Operator.doc");// 文件的存放路径// 设置输出的格式response.reset();response.setContentType("bin");response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");// 循环取出流中的数据byte[] b = new byte[100];int len;try {while ((len = inStream.read(b)) > 0)response.getOutputStream().write(b, 0, len);inStream.close();} catch (IOException e) {e.printStackTrace();}}// 下载网络文件public void downloadNet(HttpServletResponse response) throws MalformedURLException {int bytesum = 0;int byteread = 0;URL url = new URL("windine.blogdriver.com/logo.gif");try {URLConnection conn = url.openConnection();InputStream inStream = conn.getInputStream();FileOutputStream fs = new FileOutputStream("c:/abc.gif");byte[] buffer = new byte[1204];int length;while ((byteread = inStream.read(buffer)) != -1) {bytesum += byteread;System.out.println(bytesum);fs.write(buffer, 0, byteread);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}//支持在线打开文件的一种方式public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {File f = new File(filePath);if (!f.exists()) {response.sendError(404, "File not found!");return;}BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));byte[] buf = new byte[1024];int len = 0;response.reset(); // 非常重要if (isOnLine) { // 在线打开方式URL u = new URL("file:///" + filePath);response.setContentType(u.openConnection().getContentType());response.setHeader("Content-Disposition", "inline; filename=" + f.getName());// 文件名应该编码成UTF-8} else { // 纯下载方式response.setContentType("application/x-msdownload");response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());}OutputStream out = response.getOutputStream();while ((len = br.read(buf)) > 0)out.write(buf, 0, len);br.close();out.close();}

I. java下载服务器上的文件到客户端

java编程方法下载服务器上的文件到本地客服端,代码如下:

importjava.io.BufferedWriter;importjava.io.File;importjava.io.FileOutputStream;importjava.io.FileWriter;importjava.io.IOException;importjava.io.InputStream;importjava.net.URL;importjava.net.URLConnection;publicclassDownLoad{publicstaticvoiddownloadFile(URLtheURL,StringfilePath)throwsIOException{FiledirFile=newFile(filePath);if(!.exists()){//文件路径不存在时,自动创建目录dirFile.mkdir();}//从服务器上获取图片并保存URLConnectionconnection=theURL.openConnection();InputStreamin=connection.getInputStream();FileOutputStreamos=newFileOutputStream(filePath+"\123.png");byte[]buffer=newbyte[4*1024];intread;while((read=in.read(buffer))>0){os.write(buffer,0,read);}os.close();in.close();}publicstaticvoidmain(String[]args){//下面添加服务器的IP地址和端口,以及要下载的文件路径StringurlPath="http://服务器IP地址:端口/image/123.png";//下面代码是下载到本地的位置StringfilePath="d:\excel";URLurl=newURL(urlPath);try{downloadFile(url,filePath);}catch(IOExceptione){e.printStackTrace();}}}