首页 > 解决方案 > 使用 PrintStream 后 System.out.println() 未运行

问题描述

因此,我有以下代码System.out.println()从我的一种打印到控制台的方法中捕获输出,login.printAccountsByName();但之后我无法使用System.out.println()。任何帮助表示赞赏。

因此,当程序进入该if部分时,打印语句不再向控制台打印任何内容。

        PrintStream oldSysOut = System.out;
        ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
        try (PrintStream sysOut = new PrintStream(outBuf, false)) {
            System.setOut(sysOut);
            System.setErr(sysOut);

            // Logic of system.out goes here
            login.printAccountsByName();
        }
        String output = new String(outBuf.toByteArray());
        
        oldSysOut.close();
            
        BufferedReader bf = new BufferedReader(new StringReader(output));
        String line = null;

        try {
            line = bf.readLine();
            if ( !line.equals("")) {
                System.out.println("You own the following funds\n");
            login.printAccountsByName();
            
            System.out.print("\nEnter the name of the fund to sell: ");
            String option5 = input.nextLine();
            
            System.out.print("\nEnter the number of shares to sell or \"all\" to sell everything: ");
            double sellShares = input.nextDouble();
            
            login.sellShares(option5, sellShares);
            
            System.out.println("You own the following funds\n");
            login.printAccountsByName();
            
            System.out.println("Your current cash balance is $" + login.getCash());
            }

标签: java

解决方案


在您的代码中,您将默认 System.out PrintStream 更改为您创建的另一个,请参阅:

ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
try (PrintStream sysOut = new PrintStream(outBuf, false)) {
   System.setOut(sysOut);

但是您的新 PrintStream 正在写入您的 outBuf 并且您的outBuf 未连接到 Console。这就是为什么您没有看到后来触发的 System.out.println 调用的任何结果的原因之一。您可以将您的 ByteArrayOutputStream 连接到另一个 OutputStream 例如 FileOutputStream with outBuf.writeTo(...);

另一个原因是您的try-with-resource 语句关闭了您的 PrintStream

try (PrintStream sysOut = new PrintStream(outBuf, false)) {

在这个 try-block 结束时,sysOut 的 close 方法被自动触发,你的 sysOut 流被关闭并且不再打开写。


推荐阅读