当前位置: 技术问答>java相关
急急急!想找一个java 写的文件下载程序(最好用url类),那位朋友有这方面的程序或原码?100分必送?
来源: 互联网 发布时间:2015-04-02
本文导语: | public boolean downLoadFile2(String fileurl, String savepath) {//Things need to do: //Set connection timeout //Try more times to download //Catch a general Exception is not so good //... try { int httpStatusCode; URL url =new URL(/tech-qa-java/fileurl/index.html); URLConnecti...
|
public boolean downLoadFile2(String fileurl, String savepath)
{//Things need to do:
//Set connection timeout
//Try more times to download
//Catch a general Exception is not so good
//...
try
{
int httpStatusCode;
URL url =new URL(/tech-qa-java/fileurl/index.html);
URLConnection conn = url.openConnection();
conn.connect();
HttpURLConnection httpconn =(HttpURLConnection)conn;
httpStatusCode =httpconn.getResponseCode();
if(httpStatusCode!=HttpURLConnection.HTTP_OK)
{//HttpURLConnection return an error code
System.out.println("Connect to "+fileurl+" failed,return code:"+httpStatusCode);
return false;
}
int filelen = conn.getContentLength();
InputStream is = conn.getInputStream();
byte[] tmpbuf=new byte[1024];
File savefile =new File(savepath);
if(!savefile.exists())
savefile.createNewFile();
FileOutputStream fos = new FileOutputStream(savefile);
int readnum = 0;
if(filelen-1)
{
readnum = is.read(tmpbuf);
if(readnum>0)
fos.write(tmpbuf,0,readnum);
}
}
else
{
int readcount =0;
while(readcount0)
{
fos.write(tmpbuf,0,readnum);
readcount =readcount +readnum;
}
}
if(readcount
{//Things need to do:
//Set connection timeout
//Try more times to download
//Catch a general Exception is not so good
//...
try
{
int httpStatusCode;
URL url =new URL(/tech-qa-java/fileurl/index.html);
URLConnection conn = url.openConnection();
conn.connect();
HttpURLConnection httpconn =(HttpURLConnection)conn;
httpStatusCode =httpconn.getResponseCode();
if(httpStatusCode!=HttpURLConnection.HTTP_OK)
{//HttpURLConnection return an error code
System.out.println("Connect to "+fileurl+" failed,return code:"+httpStatusCode);
return false;
}
int filelen = conn.getContentLength();
InputStream is = conn.getInputStream();
byte[] tmpbuf=new byte[1024];
File savefile =new File(savepath);
if(!savefile.exists())
savefile.createNewFile();
FileOutputStream fos = new FileOutputStream(savefile);
int readnum = 0;
if(filelen-1)
{
readnum = is.read(tmpbuf);
if(readnum>0)
fos.write(tmpbuf,0,readnum);
}
}
else
{
int readcount =0;
while(readcount0)
{
fos.write(tmpbuf,0,readnum);
readcount =readcount +readnum;
}
}
if(readcount