private static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return; // swallow a 404
} catch (IOException e) {
return; // swallow a 404
}
}
关于下载
下载文件的Java实现
本文提供了一个使用Java编写的简单示例,展示了如何从指定URL下载文件并保存到本地磁盘的方法。通过打开URL连接,读取远程文件内容,并将其写入到本地文件中。

被折叠的 条评论
为什么被折叠?



