Open a URL or File as an InputStream - Java java.io

Java examples for java.io:InputStream Read

Description

Open a URL or File as an InputStream

Demo Code

import java.io.FileInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class Main {
  public static void main(String[] argv) {
    String source = "http://java2s.com";
    System.out.println(openTextStream(source));
  }//from w w  w.j a  va2 s  .c o m

  /**************************************************************************
   * Open a URL or File as an InputStream
   **************************************************************************/
  static public InputStream openTextStream(String source) {
    java.io.InputStream in = null;
    java.net.URL url = null;

    // Try to open URL connection first
    try {
      try {
        url = new URL(source);
        in = url.openStream();
      } catch (MalformedURLException e) {
        // Try to open plain file, if `configFile' is not a
        // URL specification
        in = new FileInputStream(source);
      }
    } catch (java.io.IOException ex) {

    }
    return in;
  }
}

Related Tutorials