Main Content

Flexibility in input - read from file, web resource or keyboard

Archive - Originally posted on "The Horse's Mouth" - 2015-02-08 11:57:34 - Graham Ellis

When you're writing a program, don't think that you're reading from a file - think that you're reading from a stream. That gives you the flexibiity to read from a file, or from a web resource, or from a device such as a keyoard.

A stream is an input flow of data that comes to you, record by record (typically line by line) and each time you call for a record / line to be read, the next one will come to you. And when you reach the end of your data, you'll get back some sort of end-of-file signal to tell you that you're done.

Towards the end of last week's (Java) course, I wrote an example (source [here]) which would read either from a file, or from a URL (web resource / page). The initial opening of the resource differs, but once I have my Input Stream Reader, or a subclass of it, I can then use common code to handle the buffering of the data and the passing back of it to my application line by line.

In order to make the example clear, I didn't do anything fancy on the resource name the user types in to see if it looks like a file name or URL - I have him specify. Here's my resource opening code:

  import java.io.*;
  import java.net.*;
  
  try {
    if (args[0].equals("w"))
    instream = new InputStreamReader((new URL(args[1])).openStream());
    if (args[0].equals("f"))
    instream = new FileReader(args[1]);
  } catch (Exception e) {
    System.err.println(e);
  }
  
  if (instream == null) {
    System.err.println("Usage: java Stations w|f url|filename");
    System.exit(1);
  }


Common code then sets this stream up to be buffered, so that I can read it line by line:

  BufferedReader source = new BufferedReader(instream);

And further common code allows me to loop through the resource while data is still available:

  String lyne;
  while ((lyne = source.readLine()) != null) {