网页中得文本内容可以使用爬虫技术,但是当我们想将页面中得图片也保存的话,就需要使用下面这段代码,将图片直接存入本地磁盘,然后将图片的路径写入数据库。
package action;
02
03 import java.io.DataInputStream;
04 import java.io.DataOutputStream;
05 import java.io.FileOutputStream;
06 import java.net.HttpURLConnection;
07 import java.net.URL;
08
09 public class Getpic {
10 public Getpic() {
11 }
12
13 public static boolean saveUrlAs(String fileUrl, String savePath)/* fileUrl网络资源地址 */
14 {
15
16 try {
17 /* 将网络资源地址传给,即赋值给url */
18 URL url = new URL(fileUrl);
19
20 /* 此为联系获得网络资源的固定格式用法,以便后面的in变量获得url截取网络资源的输入流 */
21 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
22 DataInputStream in = new DataInputStream(connection.getInputStream());
23
24 /* 此处也可用BufferedInputStream与BufferedOutputStream 需要保存的路径*/
25 DataOutputStream out = new DataOutputStream(new FileOutputStream(savePath));
26
27
28 /* 将参数savePath,即将截取的图片的存储在本地地址赋值给out输出流所指定的地址 */
29 byte[] buffer = new byte[4096];
30 int count = 0;
31 while ((count = in.read(buffer)) > 0)/* 将输入流以字节的形式读取并写入buffer中 */
32 {
33 out.write(buffer, 0, count);
34 }
35 out.close();/* 后面三行为关闭输入输出流以及网络资源的固定格式 */
36 in.close();
37 connection.disconnect();
38 return true;/* 网络资源截取并存储本地成功返回true */
39
40 } catch (Exception e) {
41 System.out.println(e + fileUrl + savePath);
42 return false;
43 }
44 }
45
46 public static void main(String[] args) {
47 Getpic pic = new Getpic();/* 创建实例 */
48
49 //需要下载的URL
50 String photoUrl = "http://hiphotos.baidu.com/yanshennan/pic/item/03a505c8bcbaf6557f3e6f8a.jpg";
51
52 // 截取最后/后的字符串
53 String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));
54
55 //图片保存路径
56 String filePath = "E:";
57
58 /* 调用函数,并且进行传参 */
59 boolean flag = pic.saveUrlAs(photoUrl, filePath + fileName);
60
61 System.out.println("Run ok!\n Get URL file " + flag);
62 System.out.println(filePath);
63 System.out.println(fileName);
64 }
65
66 }
原文地址:http://www.open-open.com/lib/view/open1329995970842.html