Read from URL

In this chapter you will learn:

  1. How to read from URL with InputStreamReader
  2. Getting an Image from a URL

Read from URL with InputStreamReader

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
/*from  j  ava 2 s. co m*/
public class Main {

  public static void main(String[] args) throws Exception {

    URL u = new URL("http://www.java2s.com");
    InputStream in = u.openStream();

    in = new BufferedInputStream(in);

    Reader r = new InputStreamReader(in);
    int c;
    while ((c = r.read()) != -1) {
      System.out.print((char) c);
    }
  }

}

The code above generates the following result.

Getting an Image from a URL

import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;
/*jav  a  2  s  .  com*/
public class Main {
  public static void main(String[] argv) throws Exception {
    URL url = new URL("http://hostname:80/image.gif");

    Image image = Toolkit.getDefaultToolkit().getDefaultToolkit().createImage(url);
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to find out the URL Equality
Home » Java Tutorial » URL URI
URL
URL Creation
URL for jar file
URL Components
Convert file path to URL
URL Relative
URL Protocol
Read from URL
Compare URL
URLConnection
HTTP Header
URLConnection Post
Cookie
URLConnection Read
HttpURLConnection
HttpURLConnection Properties
HttpURLConnection proxy
HttpURLConnection Authenticator
HTTPS
JarURLConnection
Encode a URL
Decode a URL
URI
URI Normalization
URI Resolution
URI Relativization
Convert URI to URL
IP Address
IP Ping
NetworkInterface