java - 如果我想做输出,Scanner/System.in 的模拟是什么?
问题描述
如果我使用 Scanner 类型来读取 System.out,我可以轻松地从 System.in 切换到某个文件,因此我可以测试使用输入的方法。
String line;
Scanner in = new Scanner(System.in); // reading from the command line
// or
File file = new File(someFileName);
in = new Scanner(file); // reading from the file
System.out.print("Type something: ");
line = in.nextLine();
System.out.println("You said: " + line);
但是,如果我希望我的方法交替写入文件或 System.out,我可以将什么类型用于输出的相同开关?
解决方案
System.out
是一个PrintStream
。您始终可以创建自己的 PrintStream 来写入文件。
PrintStream out = System.out;
out.print("Write to console");
out = new PrintStream(new File("path"));
out.print("Write to file");
小心点。System.out
不应该关闭,而PrintStream
从文件创建的应该关闭。
推荐阅读
- c++ - 什么是满足 SOLID 原则的好 C++98 类回调机制?
- c# - 发送到统一 webGl 的实时值
- swift - UIRefreshControl's tintColor can't be initially set
- html - 占位符在 Textarea 中不可见
- c# - 软删除的子对象出现在父对象列表中
- google-cloud-platform - 如何监控 BigQuery 表是否包含当前数据并在不包含时发送警报?
- flutter - 如何在 initState 中等待异步
- sql - 如何计算结果行数plsql
- javascript - 测试框架意外退出 - 空手道测试
- php - 文本文件未写入服务器