public void downloadFile(String url) {
try {URL path = null;
try {
path = new URL(url);
} catch (Exception e) {
System.out.println("Error input url");
}
String fileName = url.substring(url.lastIndexOf("/")+1);
FilterInputStream in = (FilterInputStream) path.openStream();
File fileOut = new File("d:\\Temp\\"+fileName);
FileOutputStream out = new FileOutputStream(fileOut);
byte[] bytes = new byte[1024];
int c;
while ((c = in.read(bytes)) != -1) {
out.write(bytes, 0, c);
}
in.close();
out.close();
} catch (Exception e) {
System.out.println("Error!");
throw new RuntimeException(e);
}
}
@Test
public void test(){
downloadFile("http://imgsrc.baidu.com/baike/pic/item/f765756053ce5274eaf8f80b.jpg");
}
本文介绍了一个简单的文件下载方法实现过程,通过Java代码演示了如何从指定URL下载文件并保存到本地磁盘。该方法首先解析URL获取文件名,然后通过输入流读取网络资源,并使用输出流将文件写入本地指定路径。

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



