- 利用指定的URL在本地显示网络上图片的例子
-
import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; /* 在控制台打印指定URL的图片 */ public class URLdemo1 { public static void main(String[] args) throws Exception { //图片的网络地址 URL url=new URL("http://i2.sinaimg.cn/dy/870/2012/1201/U8843P1T870D1F22365DT20130420222132.jpg"); BufferedInputStream bis=new BufferedInputStream(url.openStream()); //字节数组输出流,将所有内容放在字节数组中 ByteArrayOutputStream baos=new ByteArrayOutputStream(); int i; while((i=bis.read())!=-1){ baos.write(i); } bis.close(); JFrame jf=new JFrame("图片显示窗体"); jf.setBounds(30, 30, 300, 300); //通过ImageIcon将字节数组组解码为图片,放入JLabel组件中 JLabel labImg=new JLabel(new ImageIcon(baos.toByteArray())); jf.getContentPane().add(labImg); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setVisible(true); } }
- 1-2 一个将新浪新闻的首页HTML代码打印在控制台的例子
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; //在控制台打印新浪新闻的首页HTML 代码 public class URLdemo { public static void main(String[] args) throws UnsupportedEncodingException, IOException { URL url=new URL("http://news.sina.com.cn"); BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream(),"GBK")); String s; while((s=br.readLine())!=null){ System.out.println(s); } br.close(); // 关闭资源 } }
原文链接:http://020618.blog.51cto.com/6098149/1183036
文章评论