首页 > 解决方案 > 如果我想做输出,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,我可以将什么类型用于输出的相同开关?

标签: javajava.util.scannersystem.outsystem.in

解决方案


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从文件创建的应该关闭。


推荐阅读