Java I/O How to - Open Stream from URL and output its content








Question

We would like to know how to open Stream from URL and output its content.

Answer

        /* w  ww .j  a v a  2 s  .c o  m*/

import java.net.*;
import java.io.*;

public class MainClass {

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

    InputStream in = null;
    try {
      URL u = new URL("http://www.java2s.com");
      in = u.openStream();
      for (int c = in.read(); c != -1; c = in.read()) {
        System.out.write(c);
      }
      in.close();
    } 
    catch (MalformedURLException ex) {
      System.err.println("not a URL Java understands.");
    }
    finally {
      if (in != null) in.close();
    }
  }
}

The code above generates the following result.