learning java 重定向标准输入输出

output redirectionOut:

public class RedirectOut {
    public static void main(String[] args) throws FileNotFoundException {
        try {
            var ps = new PrintStream(new FileOutputStream("out.txt"));
            System.setOut(ps);
            System.out.println("普通字符串");
            System.out.println(new RedirectOut());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

input redirectionIn:

public class RedirectionIn {
    public static void main(String[] args) {
        try {
            var fis = new FileInputStream("./src/com/company/RedirectionIn.java");
            System.setIn(fis);
            var sc = new Scanner(System.in);
            sc.useDelimiter("
");
            while (sc.hasNext()){
                System.out.println("键盘输入的内容是:" + sc.next());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
原文地址:https://www.cnblogs.com/lianghong881018/p/11302620.html