Buffered Reader Exception
I cant understand where my program has gone wrong. It produces this error
deps-jar:
compile:
run:
IO Error! Stream closed
java.io.IOException: Stream closed
at java.io.BufferedReader.ensureOpen(BufferedReader.j ava:97)
at java.io.BufferedReader.readLine(BufferedReader.jav a:292)
at java.io.BufferedReader.readLine(BufferedReader.jav a:362)
at lab8.main(lab8.java:33)
BUILD SUCCESSFUL (total time: 0 seconds)
Here is the source code
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Scanner;
import java.io.*;
public static void main(String[] args) {
try{
Scanner sc = new Scanner (System.in);
//Step 1: create and open file stream
FileReader openfile = new FileReader ("names.txt");
BufferedReader brstream = new BufferedReader (openfile);
//Step 2 : must write into new file
FileWriter fw1= new FileWriter ("small.txt");
BufferedWriter bw1 = new BufferedWriter (fw1);
PrintWriter pw1 = new PrintWriter (bw1);
FileWriter fw2= new FileWriter ("big.txt");
BufferedWriter bw2 = new BufferedWriter (fw2);
PrintWriter pw2 = new PrintWriter (bw2);
//Step 3: check length of name
String name = brstream.readLine();
while ( (brstream.readLine() != null) ){
if (name.length() < 5)
{pw1.println(name);}
else { pw2.println(name) ; }
//step 4: close all the stream
brstream.close();
pw1.close();
pw2.close(); } //close while
} //close try
catch(FileNotFoundException e)
{System.out.println("File not found!"+e.getMessage() );
System.exit(0);}
catch(IOException e)
{System.out.println("IO Error! "+ e.getMessage());
e.printStackTrace();
System.exit(0);}
}
}
Basically this program reads a text file "names.txt". There is one name in each line of the file with no whitespace characters. If the length of the name is less than 5, it is printed in "small.txt" else it is printed in "big.txt". Can anybody tell me what is wrong with my program?