您的位置:首页 > 理论基础 > 计算机网络

从网络上下载文件到本地

2015-08-10 13:34 621 查看
下载:

void downloadDemo() {
String fileName = "E:" + File.separator + "test" + File.separator
+ "baidu.png";
URL url = null;
HttpsURLConnection connection = null;
File file = new File(fileName);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
InputStream is = null;
OutputStream os = null;
byte[] b = new byte[1024];
int len = 0;
try {
url = new URL("https://www.baidu.com/img/bdlogo.png");
connection = (HttpsURLConnection) url.openConnection();
is = connection.getInputStream();
os = new FileOutputStream(file);
while ((len = is.read(b)) != -1) {
os.write(b, 0, len);
//System.out.println(len);
}
System.out.println("download complete!" + file.length() + "   "
+ connection.getContentLength());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
is.close();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: