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

烈酒焚心 提交于 2020-07-31 05:18:18

问题


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();

    }
    }

回答1:


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!!)



来源:https://stackoverflow.com/questions/44518912/system-out-println-not-working-after-printwriter-on-system-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!