java - 使用 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());
}
解决方案
在您的代码中,您将默认 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 流被关闭并且不再打开写。
推荐阅读
- json - TypeError:links.map 不是 React 函数
- java - JavaFX 传递参数
- node.js - Firebase 验证 ID 令牌的奇怪行为
- mapbox - 从 MapBox GL 徽标中删除不必要的阴影
- ffmpeg - FFMPEG 视频缩放到位置 XY
- javascript - 滚动上的视差元素
- r - 如何在 wordpress 网站中显示闪亮代理应用程序
- c - 简单的 OpenMP 循环在缩放时非常慢
- r - 在 R 数据框列中随机分布一个向量
- javascript - electron.js 标题栏问题:Uncaught ReferenceError: require is not defined at titleBarStuff.js:1