user2757415
user2757415

Reputation: 153

System.out.println not working after printWriter on System.out

I am facing a rather unusual situation. I am using printWriter with System.out to print the bytes from a file onto console, first using a ByteStreamReader and then a CharacterStreamReader. The problem is after the output of ByteStreamReader, subsequent System.out.println statements are not printing anything on console. I tried using flush on System.out.flush() but still not getting output.

Code:

FileStream fs = new FileStream(); //ByteStreamReader
String source = "./test_zh.txt";
CharacterStream cs = new CharacterStream(); //CharacterStreamReader
System.out.println("\nChinese Sentence using ByteStreamReader");
fs.printOnConsole(source); //if i comment this, then below lines gets printed 
System.out.println("\nChinese Sentence using CharacterStreamReader");//Not getting printed on console
cs.printOnConsole(source); //Not getting printed on console

My code for both the Stream types is as follows:

FileSteam Class

public void printOnConsole(String source) throws IOException{
try{
    inp = new FileInputStream(source);
    pwr = new PrintWriter(System.out,true);
    int c =0;

    while( (c = inp.read()) != -1){
        pwr.write(c);
        pwr.write("(" + c +")");
    }
}catch(FileNotFoundException f){

}catch(IOException e){

}finally{
    inp.close();
    pwr.flush();
    pwr.close();

}
}

CharacterStream Class

    public void printOnConsole(String source) throws IOException{
    try{
        fReader = new FileReader(source);
        pwr     = new PrintWriter(System.out,true);
        int c;
        while((c = fReader.read()) != -1){
            pwr.write(c);
            pwr.write("(" +c +")");
        }

    }catch(IOException f){

    }finally{
        fReader.close();
        pwr.flush();
        pwr.close();

    }
    }

Upvotes: 1

Views: 2154

Answers (1)

Stephen C
Stephen C

Reputation: 718768

I can see 2 significant problems with your FileStream and CharacterStream classes.

  • Both classes call close() on the PrintWriter that wraps System.out. When that happens System.out will be closed, and no further writes to it will be permitted.

  • Both classes squash IO exceptions. That is they catch the exception, say nothing, and continue as if nothing happened. That is extremely poor coding practice ... and it is most likely hiding the exceptions that happen when you write to the closed System.out stream.

There are also a variety of style problems, the worst of which is your poor choice of method and class names. For example the printOnConsole methods don't print on the console. Rather they print on the standard output stream ... which may go to somewhere other than the console. (And your application can't tell!!)

Upvotes: 3

Related Questions