当前位置: 技术问答>java相关
怎样用java来实现文件下载?
来源: 互联网 发布时间:2015-04-02
本文导语: net包中提供了这样的类吗? 谢谢了~~~~~~~~ | //Download by HTTP //For other protocol, do it yourself import java.net.*; import java.io.*; public class DownLoad { public static void main(String args[]) { DownLoad dl =new...
net包中提供了这样的类吗?
谢谢了~~~~~~~~
谢谢了~~~~~~~~
|
//Download by HTTP
//For other protocol, do it yourself
import java.net.*;
import java.io.*;
public class DownLoad
{
public static void main(String args[])
{
DownLoad dl =new DownLoad();
String downfile ="http://moviesky.8u8.com/cool.htm"; // can be any file type! Not only htm files can be downloaded.
String saveplace ="c:\test111.htm";
if(dl.downLoadFile(downfile,saveplace))
System.out.println("Download ok");
}
public boolean downLoadFile(String fileurl, String savepath)
{
try
{
URL url =new URL(/tech-qa-java/fileurl/index.html);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
int filelen = conn.getContentLength();
byte[] filebuf =new byte[filelen];
byte[] tmpbuf =new byte[1024];
int readcount =0;
int readnum = 0;
while(readcount-1)
{
System.arraycopy(tmpbuf,0,filebuf,readcount,readnum);
readcount =readcount +readnum;
}
}
if(readcount0)
fos.write(tmpbuf,0,readnum);
}
}
else
{
int readcount =0;
while(readcount-1)
{
fos.write(tmpbuf,0,readcount);
readcount =readcount +readnum;
}
}
if(readcount
//For other protocol, do it yourself
import java.net.*;
import java.io.*;
public class DownLoad
{
public static void main(String args[])
{
DownLoad dl =new DownLoad();
String downfile ="http://moviesky.8u8.com/cool.htm"; // can be any file type! Not only htm files can be downloaded.
String saveplace ="c:\test111.htm";
if(dl.downLoadFile(downfile,saveplace))
System.out.println("Download ok");
}
public boolean downLoadFile(String fileurl, String savepath)
{
try
{
URL url =new URL(/tech-qa-java/fileurl/index.html);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
int filelen = conn.getContentLength();
byte[] filebuf =new byte[filelen];
byte[] tmpbuf =new byte[1024];
int readcount =0;
int readnum = 0;
while(readcount-1)
{
System.arraycopy(tmpbuf,0,filebuf,readcount,readnum);
readcount =readcount +readnum;
}
}
if(readcount0)
fos.write(tmpbuf,0,readnum);
}
}
else
{
int readcount =0;
while(readcount-1)
{
fos.write(tmpbuf,0,readcount);
readcount =readcount +readnum;
}
}
if(readcount