中国法治在线_中国法治在线网 > 主持人

JAVA程序下载网络图片

时间:2018-03-12 17:33

来源:作者:点击:

package action; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileOutputStream; import java.net.HttpURLConnection; import java.net.URL; public class Getpic { public Getpic() { } public static boolean saveUrlAs(String fileUrl, String savePath)/* fileUrl网络资源地址 */ { try { /* 将网络资源地址传给,即赋值给url */ URL url = new URL(fileUrl); /* 此为联系获得网络资源的固定格式用法,以便后面的in变量获得url截取网络资源的输入流 */ HttpURLConnection connection = (HttpURLConnection) url.openConnection(); DataInputStream in = new DataInputStream(connection.getInputStream()); /* 此处也可用BufferedInputStream与BufferedOutputStream 需要保存的路径*/ DataOutputStream out = new DataOutputStream(new FileOutputStream(savePath)); /* 将参数savePath,即将截取的图片的存储在本地地址赋值给out输出流所指定的地址 */ byte[] buffer = new byte[4096]; int count = 0; while ((count = in.read(buffer)) > 0)/* 将输入流以字节的形式读取并写入buffer中 */ { out.write(buffer, 0, count); } out.close();/* 后面三行为关闭输入输出流以及网络资源的固定格式 */ in.close(); connection.disconnect(); return true;/* 网络资源截取并存储本地成功返回true */ } catch (Exception e) { System.out.println(e + fileUrl + savePath); return false; } } public static void main(String[] args) { Getpic pic = new Getpic();/* 创建实例 */ //需要下载的URL String photoUrl = "http://hiphotos.baidu.com/yanshennan/pic/item/03a505c8bcbaf6557f3e6f8a.jpg"; // 截取最后/后的字符串 String fileName = photoUrl.substring(photoUrl.lastIndexOf("http://www.open-open.com/")); //图片保存路径 String filePath = "E:"; /* 调用函数,并且进行传参 */ boolean flag = pic.saveUrlAs(photoUrl, filePath + fileName); System.out.println("Run ok!\n Get URL file " + flag); System.out.println(filePath); System.out.println(fileName); } }
扩展阅读java取网络图片并缩小
Java资源大全中文版
Java编程入门 - 前言

Android实战之你应该使用哪个网络库?
为您推荐java取网络图片并缩小
Java Servlet完全教程
通过jcifs实现java访问网络共享文件
Java常见问题集锦(来自Sun中国官方站)
如何为可扩展系统进行Socket编程
更多JAVA
Java开发

(此文不代表本网站观点,仅代表作者言论,由此文引发的各种争议,本网站声明免责,也不承担连带责任。)

【责任编辑:admin】
热图 更多>>
热门文章 更多>>
中国法治在线Copyright © 2002-2019 中国法治在线 版权所有
邮箱:2622293504@qq.com