引用 1
游客 [ IP:117.9.83.* ]
2008-11-13 17:01:01 
如何通过java程序去下载文件如何通过java程序去远端下载文件呢?比如用户给你一个地址,让你去下载文件,怎么做呢?下面模拟一个例子。假设:用户给你的地址是http://localhost:8080/ICCardQueryR2003-02-01.zi ...

如何通过java程序去下载文件
如何通过java程序去远端下载文件呢?比如用户给你一个地址,让你去下载文件,怎么做呢?下面模拟一个例子。
假设:用户给你的地址是http://localhost:8080/ICCardQueryR2003-02-01.zip
1、一般的下载
我们在java的main方法里写这么段代码
// 定义httpURLConnection 初始为null
HttpURLConnection hc = null;

try ...{
// 打开一个http连接
URL url = new URL(
"http://localhost:8080/ICCardQueryR2003-02-01.zip");
hc = (HttpURLConnection) url.openConnection();

// 定义输入流
InputStream instream = hc.getInputStream();

// 创建这个文件输出流
String tempFileName = "1.zip";
FileOutputStream fos = new FileOutputStream(tempFileName);

// 定义一个大小为1024的字节数组
byte[] buf = new byte[1024];

// 从输入流中读出字节到定义的字节数组
int len = instream.read(buf 0 1024);

// 循环读入字节,然后写到文件输出流中
while (len != -1) ...{
fos.write(buf 0 len);
len = instream.read(buf 0 1024);

}
fos.flush();
fos.close();

} catch (Exception e) ...{
System.err.println("下载出错!");

} finally ...{
if (hc != null)
hc.disconnect();
}


上面这段代码是能够该文件的下载的。这里我们假设的这个url http://localhost:8080/ICCardQueryR2003-02-01.zip 比较特殊,我们这里用的tomact,这个文件要放在webapp下面的root 根目录下面。在现实的应用当中,用户可能给你一个包含jsp或者servlet的地址,但是这个你放心,用户到后来一般会给你文件的,有些是通过转向,有的是通过直接给你输入流。
写到了这里,我们是不是会问,如果我们下了一会没完全下来怎么办呢,那我们要写一个能支持断点续传的类,如下面代码。
2、支持断点续传的下载
/** *//**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException ...{
// 定义httpURLConnection 初始为null
HttpURLConnection hc = null;
URL url = null;
String tempFileName = "1.zip";
String sUrl = "http://localhost:8080/ICCardQueryR2003-02-01.zip";

long beginPos = 0;
long fileLength = 0;
int num = 0;
boolean isFinish = false;
boolean isFirst = true;
while (!isFinish &&num 0) ...{
beginPos += len;
ras.write(buf 0 len);
len = instream.read(buf 0 1024);
}

ras.close();
if (beginPos >= fileLength) ...{
isFinish = true;
}

} catch (MalformedURLException e) ...{
System.err.println(e.getMessage());
} catch (IOException e) ...{
System.err.println(e.getMessage());
} finally ...{
num++;
hc.disconnect();
}
}

}

/** *//**
* 从HttpURLConnection中得到文件长度,此HttpURLConnection为已经开启连接后的状态
*
* @param hc
* @return long
*/
private static long getFileLength(HttpURLConnection hc) ...{
long nFileLength = -1;
for (int i = 1;; i++) ...{
String sHeader = hc.getHeaderFieldKey(i);
if (sHeader != null) ...{
if (sHeader.equals("Content-Length")) ...{
nFileLength = Long.parseLong(hc.getHeaderField(sHeader));
break;
}
} else ...{
break;
}
}

return nFileLength;
}

关键词:程序  文件  下载  
验证码:
  
美女(2897)  网站(1509)  下载(1499)  空间(1185)  歌曲(1148)  如何(1099)  免费(1050)  经典(1048)  小说(985)  广告(976)  赚钱(971)  创业(954)  方法(927)  网络(916)  视频(906)  电影(872)  手机(872)  最新(847)  旅游(799)  奥运(787)  游戏(772)  云南(744)  博客(737)  云南旅游(701)  个性(700)  蛋糕(693)  大全(690)  十大(640)  介绍(633)  富豪(630)