// CSE 143, Winter 2011, Marty Stepp // This program demonstrates input streams by reading from a file and from a URL. // It also demonstrates the try/catch syntax for handling exceptions. import java.io.*; import java.net.*; import java.util.*; public class ReadFile { public static void main(String[] args) { // read data from a file Scanner console = new Scanner(System.in); System.out.print("File name? "); String filename = console.nextLine(); try { readAll(new FileInputStream(filename)); System.out.println(countWords(new FileInputStream(filename))); } catch (IOException fred) { System.out.println("Something went wrong while reading the file: " + fred.getMessage()); } // read data from a URL try { URL u = new URL("http://www.purple.com/"); InputStream urlInput = u.openStream(); readAll(urlInput); System.out.println(countWords(u.openStream())); } catch (IOException ivonna) { System.out.println("The URL is bad"); } } // Reads the entire contents of the given input stream (which could be // a file, web site, etc.) and prints them all out to the console. // Throws an IOException if anything goes wrong while reading data. // Precondition: in != null public static void readAll(InputStream in) throws IOException { while (true) { int b = in.read(); if (b == -1) { break; } char c = (char) b; System.out.print(c); } } // Returns a count of the total number of words (delimited by whitespace) // found in the given input stream. // Precondition: in != null public static int countWords(InputStream in) { Scanner input = new Scanner(in); int count = 0; while (input.hasNext()) { input.next(); count++; } return count; } }