FileDocCategorySizeDatePackage
BufferedReadErrors.javaAPI DocExample1956Fri Feb 15 12:07:58 GMT 2002testbufferedreader

BufferedReadErrors.java

package testbufferedreader;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

class TestBufferedReader extends JFrame{

	private JTextArea j = new JTextArea();
	private Container c;
	public TestBufferedReader() {
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				dispose();
				System.exit(0);
			}
		});
		// 
		c = getContentPane();
		// add the only control to the content pane
		c.add(j);
	}


    public void readFile() throws IOException {
    	// Open the file
//		File inFile     = new File("c:\\limerick.txt");
    	// Create a file stream, wrapping the file
//    	FileReader fileReader = new FileReader(inFile);
    	// Create a second wrapper,
//    	BufferedReader bufReader  = new BufferedReader(fileReader);
		BufferedReader bufReader = new BufferedReader(
			new FileReader(
				new File("c:\\limerick.txt")));
    	// Read in the first line...
    	String s;
    	// Tries to read forever
    	while (true) {
    		s = bufReader.readLine();
    		// a null reference is returned if the end of file 
    	   	// has been reached.  
    	   	if(s == null) throw new EOFException("Hello, end-of-file reached");
           	// Add the new string to the text area
           	j.append(s);
           	j.append("\n");  // Append a new line to make it look nice
		}
    }


	public static void main(String args[])  {
		System.out.println("Starting TestBufferedReader...");
		TestBufferedReader mainFrame = new TestBufferedReader();
		mainFrame.setSize(400, 400);
		mainFrame.setTitle("TestBufferedReader");
		mainFrame.setVisible(true);
		// Lets add error detection
		try {
		  mainFrame.readFile();
		}
      	catch (FileNotFoundException e) {
			System.out.println("Warning, FileNotFound exception raised"+e);
		}
		catch (IOException e) {
			System.out.println("Warning, I/O exception "+e);
		}
	}
}