如果我使用Scanner类型来读取System。在外面,我可以很容易地从系统切换。
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
从一个文件创建应该被关闭。