【问题标题】:System.out.println not working after printWriter on System.outSystem.out.println 在 System.out 上的 printWriter 后不起作用
【发布时间】:2017-06-13 10:28:55
【问题描述】:

我正面临一个相当不寻常的情况。我正在使用printWriterSystem.out 将文件中的字节打印到控制台上,首先使用ByteStreamReader,然后使用CharacterStreamReader。问题是在ByteStreamReader 的输出之后,随后的System.out.println 语句没有在控制台上打印任何内容。我尝试在System.out.flush() 上使用flush,但仍然没有得到输出。

代码:

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

我的两种 Stream 类型的代码如下:

FileSteam 类

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 类

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

    }
    }

【问题讨论】:

  • 可能发生的事情是您对.close() 的调用之一在内部关闭了它委托给的流,因此它关闭了System.out
  • 您可能遇到了异常。尝试在所有catch 中添加f.printStackTrace()

标签: java printwriter system.out


【解决方案1】:

我发现您的 FileStreamCharacterStream 课程存在 2 个重大问题。

  • 两个类都在包裹System.outPrintWriter 上调用close()。发生这种情况时,System.out 将被关闭,并且不允许进一步写入。

  • 两个类squash IO 异常。那就是他们捕捉到异常,什么也不说,然后继续,就好像什么都没发生一样。这是极差的编码实践……而且它很可能隐藏了当您写入关闭的System.out 流时发生的异常。

还有各种各样的样式问题,其中最糟糕的是您对方法和类名的选择不当。例如 printOnConsole 方法不在控制台上打印。相反,它们在标准输出流上打印......可能会转到控制台以外的其他地方。 (而且你的应用程序无法分辨!!)

【讨论】:

  • 感谢您的意见。
  • 我明白了,你的第一点。关于第二点,我试图测试一些东西并编写一个非常简单的程序,因此没有费心在 catch 块中打印异常,但现在既然你指出了,我明白这是我的错误。
  • 事情是这样的:由于不“被打扰”来正确处理异常,您实际上最终得到的代码表现得莫名其妙,并且浪费了(我猜)几个小时。更好的策略:如果您不在乎,则使用throws 允许传播异常。无声挤压几乎总是一个坏主意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-26
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
相关资源
最近更新 更多