前任的代码,没有注释解说,没有文档,以前没用过这种方式,只能慢慢测试,然而项目着急,哪位大神有时间指导一下,大概的工作原理就行,,,
public static void downloadFile(String fileUrl, String localFile)
throws java.io.IOException {
java.io.FileOutputStream fos = null;
java.io.BufferedInputStream bis = null;
try {
bis = getstream(fileUrl);
java.io.File file_in = new java.io.File(localFile);
fos = new java.io.FileOutputStream(file_in);
byte[] bytes = new byte[4096];
int c;
while ((c = bis.read(bytes)) != -1) {
fos.write(bytes, 0, c);
}
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
}
}
if (bis != null) {
try {
bis.close();
} catch (Exception e) {
}
}
}
}
private static java.io.BufferedInputStream getstream(String fileUrl)
throws java.io.IOException {
java.io.BufferedInputStream bis;
java.net.URL url1 = new java.net.URL(fileUrl);
java.net.HttpURLConnection huc = (java.net.HttpURLConnection) url1
.openConnection();
bis = new java.io.BufferedInputStream(huc.getInputStream());
return bis;
}
public static void downloadFile(String fileUrl, String localFile)
throws java.io.IOException {
// 以流的形式下载文件。
java.io.FileOutputStream fos = null;
java.io.BufferedInputStream bis = null;
try {
//获取下载流
bis = getstream(fileUrl);
java.io.File file_in = new java.io.File(localFile);
// 读到流中
fos = new java.io.FileOutputStream(file_in);
byte[] bytes = new byte[4096];
int c;
// 循环取出流中的数据
while ((c = bis.read(bytes)) != -1) {
fos.write(bytes, 0, c);
}
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
}
}
if (bis != null) {
try {
bis.close();
} catch (Exception e) {
}
}
}
}
private static java.io.BufferedInputStream getstream(String fileUrl)
throws java.io.IOException {
java.io.BufferedInputStream bis;
java.net.URL url1 = new java.net.URL(fileUrl);
java.net.HttpURLConnection huc = (java.net.HttpURLConnection) url1
.openConnection();
bis = new java.io.BufferedInputStream(huc.getInputStream());
return bis;
}
fileURL是目标文件的url,比如你有个text.jpg文件,它的放在tomcat/file文件夹下面,那么fileURL就是http://*.*.*.*:端口号/file/text.jpg,就是这个路径