首页 > 编程知识 正文

java图片下载,java下载linux文件

时间:2023-05-06 15:29:52 阅读:169949 作者:1255

import Java.io.buffered inputstream; importjava.io.File; importjava.io.FileOutputStream; importjava.io.OutputStream; import Java.net.httpurl connection; importjava.net.URL; importjava.net.URLConnection; importorg.apache.log4j.Logger; import com.talk web.entity.custom exception; /*** Java本机API可用于发送HTTP请求,即java.net.URL和java.net.URLConnection。 这些API很容易使用,而且使用很频繁。

但是,并不容易

*

* 1.从统一资源定位符(java.net.URL )获取连接器(java.net.URLConnection )2.设置请求的参数3 .发送请求

* 4.获取返回内容作为输入流5 .关闭输入流

*

*/

publicclasshttpconnectionutil { privatestaticloggerlogger=logger.getlogger (httpconnectionutil.class ); /**

*@paramurlPath下载路径

*下载包含*@paramfileSavePath文件名的保存目录

*@return返回下载文件

*@throwsException*/

publicstaticfiledownloadfile (string URL path,string文件save path ) throwsException {

logger.info ('进入下载文件的工具类) );

文件文件=空;

缓冲输入jmd HF=null;

输出流输出=空; try{//统一资源

URLURL=newurl(URLpath; //连接类的父类、抽象类

urlconnectionurlconnection=URL.open connection (; //http的连接类

httpurlconnectionhttpurlconnection=(httpurl connection ) urlConnection; //设置请求方法,默认为GET

httpurl connection.setrequestmethod (' get ); //设定字符编码

httpurl connection.setrequestproperty (' charset ',' UTF-8 ' ); //打开指向此URL中引用的资源的通信链路(如果尚未建立此类连接)。

httpURLConnection.connect (; //文件大小

int file length=httpurl connection.get contentlength (; //文件名

stringfilepathurl=httpurl connection.geturl ().getFile );

string file full name=file path URL.substring (file path URL.lastindexof ) file.separatorchar )1);

file full name=file full name.substring (file full name.lastindexof ('/' )1);

logger.info ('开始下载文件: ' fileFullName );

logger.info (file length---file length );

url.openConnection (;

jmd HF=newbufferedinputstream (httpurl connection.get inputstream () );

String path=fileSavePath;

文件=new文件(path; if (! file.getParentFile ().exists ) }

file.getParentFile ().mkdirs );

}

out=new file output stream (文件; int size=0; int len=0; byte[] buf=new byte[1024]; wile((size=jmdHF.read ) ) buf )!=-1({

len=size;

out.write(buf,0,size ); //打印下载百分比

if () len * 100 /文件长度) 50 ) len * 100 /文件长度) 55 ) {

logger.info ('已下载----'Len*100/fileLength'% ' )

}elseif((len*100/filelength )=98 ) )

logger.info ('已下载----'Len*100/fileLength'% ' )

(}//logger.info )下载了----'Len*100/fileLength'% ' );

}returnfile;

}catch(exceptione ) {//todo auto-generated catch block

thrownewcustomexception (e.tostring ) '文件下载异常。 请检查下载链接$$' urlPath );

(Finally ) if ) jmdHF!=null ) {

jmdhf.close (;

(if )出局!=null ) {

out.close (;

}

}

}

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。