您的位置:首页 > 其它

0009-下载远程文件

2016-02-03 10:08 288 查看
/**

* Description:通过配置IP和端口,下载对应的资源文件

* @author: chenfengyi
* @param file
* @return

*/

public boolean downLoadFromRemote(String file, String ip, String port) {

downloadPath = Thread.currentThread()
.getContextClassLoader().getResource("").getPath() + file;
String strURL = "http://" + ip + ":" + port + "/csv/downcsv.php?fileName=" + file;

LOGGER.info("开始下载资源文件[" + strURL + "],请等待……");
boolean ret = this.getRemoteFile(strURL, downloadPath);

if (ret) {
LOGGER.info("下载资源文件[" + file + "]完成");
return true;
}
LOGGER.info("下载资源[" + file + "]文件失败");
return false;
}

/**
* 通过HTTP方式获取文件,默认编码格式

* @param strUrl
* @param fileName
* @return
获取成功 true 失败 false
* @throws IOException
*/

private boolean getRemoteFile(String strUrl, String fileName){
DataInputStream input = null;
DataOutputStream output = null;
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

input = new DataInputStream(conn.getInputStream());
output = new DataOutputStream(new FileOutputStream(
fileName));
byte[] buffer = new byte[1024 * 8];
int count = 0;
while ((count = input.read(buffer)) > 0) {
output.write(buffer, 0, count);
}
return true;

} catch (IOException e) {
LOGGER.warn(e.getMessage());
return false;

} finally{
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: