public class FileDownload {
/**
* 下载文件并保存到本地
*
* @param url
* 文件在网络上的路径
* @param savePath
* 本地保存路径
*/
public static boolean download(String url, String savePath) {
boolean result = false;
File file = FileUtils.getFile(savePath);
InputStream in = null;
FileOutputStream fout = null;
try {
URL u = new URL(url);// 获得被下载文件的路径
in = u.openStream();// 打开到此 URL的连接并返回一个用于从该连接读入的 InputStream。
fout = new FileOutputStream(file);// 生成文件输出流
byte[] buffer = new byte[CommonContexts.fileBuffer];// 写文件时的缓冲区
int byteRead = 0;
while ((byteRead = in.read(buffer)) > 0) {
fout.write(buffer, 0, byteRead);
}
result = true;
} catch (Exception e) {
LoggerUtils.error(FileDownload.class.getName(), "从(" + url + ")下载文件并保存到(" + savePath + ")时出错", e);
} finally {
try {
if (in != null) {
in.close();
}
if (fout != null) {
fout.flush();
fout.close();
}
} catch (Exception e) {
FileUtils.delete(file);
}
}
return result;
}
/**
* 从网络上下载一个文件前面指定字节数的部分
*
* @param url
* 文件在网络上的路径
* @param byteSize
* 下载多少个字节
*/
public static byte[] downLoad(String url, int byteSize) {
byte[] result = new byte[byteSize];
InputStream in = null;
try {
URL u = new URL(url);
HttpURLConnection connection = (HttpURLConnection) u.openConnection();
in = connection.getInputStream();
in.read(result);
} catch (MalformedURLException e) {
LoggerUtils.error(FileDownload.class.getName(), "从(" + url + ")下载文件的前" + byteSize + "个字节时出错", e);
} catch (IOException e) {
LoggerUtils.error(FileDownload.class.getName(), "从(" + url + ")下载文件的前" + byteSize + "个字节时出错", e);
} finally {
try {
in.close();
} catch (Exception e) {
}
}
return result;
}
}