System.setOut()改变输出流对象
public static void main(String[] args ) {
try {
PrintStream out = System.out;
PrintStream ps = new PrintStream("D:/log.txt");
System.setOut(ps);
int age = 18;
System.out.println("年龄重定义成功,初始值为18");
String sex = "女";
System.out.println("性别重定义成功,初始值为女");
String info = "这是个" + sex + "孩子,应该有" + age + "岁了";
System.out.println("整合这两个变量为info字符串变量。其结果是:" + info);
System.setOut(out);
System.out.println("程序运行完毕,请查看运行日志");
} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
}
}
System.setIn()改变输入流对象
public static void main(String[] args ) {
try {
InputStream in = System.in;
InputStream ps = new FileInputStream("D:/log.txt");
System.setIn(ps);
Scanner scanner = new Scanner(System.in);
String line = "";
while (scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
}
}