开发技术-Java代码实现从网上直接下载图片或者网页

try {
   //根据String形式创建一个URL对象,
   URL url = new URL("http://www.baidu.com");
   //实列一个URLconnection对象,用来读取和写入此 URL 引用的资源
   URLConnection con = url.openConnection();
   //获取一个输入流
   InputStream is = con.getInputStream();
   //实列一个输出对象
   FileOutputStream fos = new FileOutputStream("f:/a.html");
   //一个byte[]数组,一次读取多个字节
   byte[] bt = new byte[200];
   //用来接收每次读取的字节个数
   int b = 0;

   //循环判断,如果读取的个数b为空了,则is.read()方法返回-1,具体请参考InputStream的read();
   while ((b = is.read(bt)) != -1) {
    //将对象写入到对应的文件中
    fos.write(bt, 0, b);   
   }
   //刷新流
   fos.flush();
   //关闭流
   fos.close();
   is.close();

  } catch (Exception e) {
   e.printStackTrace();
  }

将上面的代码直接复制到main方法里面运行,就OK,也可以用来下载图片,注意文件格式,如果是网页,则写成a.html,是图片则是:a.jpg,也能下载歌曲!

猜你喜欢

转载自blog.csdn.net/JustDI0209/article/details/109243778
今日推荐