您的位置:首页 > 编程语言 > Java开发

java获取远程文件(保证文件的完整性,不会出现无法打开的情况)

2013-01-30 11:36 573 查看
package com.shu.example;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUtil {
/**
* 获取远程文件
* @param remoteFilePath 远程文件路径
* @param localFilePath 本地文件路径
*/
public void getFile(String remoteFilePath,String localFilePath){
URL urlfile = null;
HttpURLConnection httpUrl = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
File f = new File(localFilePath);
/*
//如果需要设置代理时
String proxy = "192.168.224.12";
String port = "8080";
Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost",proxy);
systemProperties.setProperty("http.proxyPort",port);*/
try{
urlfile = new URL(remoteFilePath);
httpUrl = (HttpURLConnection)urlfile.openConnection();
httpUrl.connect();
bis = new BufferedInputStream(httpUrl.getInputStream());
bos = new BufferedOutputStream(new FileOutputStream(f));
int len=2048;
byte[] b = new byte[len];
while((len=bis.read(b))!=-1) {
bos.write(b, 0, len);
}
bos.flush();
bis.close();
httpUrl.disconnect();
System.out.println("done~");
}catch(Exception e){
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐