Java 文件下载方法:downloadFile() 实现详解
这段代码是一个用于从指定URL下载文件的 Java 方法,名为 downloadFile()。
方法参数:
urlStr(String): 文件的 URL 地址。filePath(String): 希望保存文件的本地路径。
代码逻辑:
- 创建
URL对象,并根据URL对象创建HttpURLConnection对象。 - 设置连接超时时间、允许输入输出、禁用缓存等属性。
- 设置请求方法为
HTTP_TYPE(可能是 GET 或 POST 等)。 - 设置请求字符集为
ENCODING_UTF_8。 - 连接到指定的 URL。
- 获取输入流
fis,读取文件内容。 - 创建输出流
fos,并将文件内容写入指定的文件路径。 - 关闭输入流、输出流和 HTTP 连接。
代码示例:
private void downloadFile(String urlStr, String filePath) {
// String urlStr = 'http://dwbillcenter.alipay.com/downloadBillFile.resource?bizType=X&userId=X&fileType=X&bizDates=X&downloadFileName=X&fileId=X';
// String filePath = '/Users/fund_bill_20160405.zip';
URL url = null;
HttpURLConnection httpUrlConnection = null;
InputStream fis = null;
FileOutputStream fos = null;
try {
url = new URL(urlStr);
httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setConnectTimeout(DOWNLOD_CON_TIMEOUT);
httpUrlConnection.setDoInput(true);
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setRequestMethod(HTTP_TYPE);
httpUrlConnection.setRequestProperty(HTTP_REQUEST_CHARSERT, ConCommConstant.ENCODING_UTF_8);
httpUrlConnection.connect();
fis = httpUrlConnection.getInputStream();
byte[] temp = new byte[1024];
int b;
fos = new FileOutputStream(new File(filePath));
while ((b = fis.read(temp)) != -1) {
fos.write(temp, 0, b);
fos.flush();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) fis.close();
if (fos != null) fos.close();
if (httpUrlConnection != null) httpUrlConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用方法:
要使用 downloadFile() 方法,您需要将 URL 地址和目标文件路径作为参数传递给该方法。例如:
String url = 'http://example.com/file.zip';
String filePath = '/path/to/file.zip';
downloadFile(url, filePath);
这将从 http://example.com/file.zip 下载文件并将其保存到 /path/to/file.zip。
注意:
DOWNLOD_CON_TIMEOUT、HTTP_TYPE和HTTP_REQUEST_CHARSERT应该被替换为实际的常量值。- 该方法可能需要一些网络权限才能正常工作。
- 下载大型文件可能会花费很长时间。
- 如果您需要处理下载进度,可以在
while循环中添加代码来更新进度条。
原文地址: https://www.cveoy.top/t/topic/o3px 著作权归作者所有。请勿转载和采集!