public class SystemIn {
public static void main(String[] args) {
try {
InputStream ps = new FileInputStream(pathToSomeFile);
System.setIn(ps);
Scanner scanner = new Scanner(System.in);
String line = "";
while (scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
Thread.sleep(TimeUnit.SECONDS.toMillis(10));
}
} catch (FileNotFoundException | InterruptedException e) {
e.printStackTrace();
}
}
}
在程序运行期间,再启动另一份代码:
public class NewSystemIn {
public static void main(String ...args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
}
}
System.setIn
只是改变了当前应用的标准输入设备,你可以使用下面的例子:在程序运行期间,再启动另一份代码:
在程序1输出自定义输入设备中的内容时,程序2依旧表现正常(能读取键盘的输入)。
键盘不会这么轻松实现的。