IO:重定向标准输入流
package net.nyist.io;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
public class RedirectIn {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream(
"src/net/nyist/io/RedirectIn.java");
) {
// 将标准输入重定向到fis输入流中
System.setIn(fis);
// 获取键盘标准输入
Scanner sc = new Scanner(System.in);
// 只把回车作为分隔符
sc.useDelimiter("\n");
// 判断是否还有下一个输入项
while (sc.hasNext()) {
// 输出输入项
System.out.println("键盘的输入内容为:" + sc.next());
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
不会等待用户输入,则将会直接输出RedirectIn.java的内容
以下是输出结果:
键盘的输入内容为:package net.nyist.io;
键盘的输入内容为:
键盘的输入内容为:import java.io.FileInputStream;
键盘的输入内容为:import java.io.IOException;
键盘的输入内容为:import java.util.Scanner;
键盘的输入内容为:
键盘的输入内容为:public class RedirectIn {
键盘的输入内容为:
键盘的输入内容为: public static void main(String[] args) {
键盘的输入内容为:
键盘的输入内容为: try (FileInputStream fis = new FileInputStream(
键盘的输入内容为: "src/net/nyist/io/RedirectIn.java");
键盘的输入内容为:
键盘的输入内容为: ) {
键盘的输入内容为: // 将标准输入重定向到fis输入流中
键盘的输入内容为: System.setIn(fis);
键盘的输入内容为:
键盘的输入内容为: // 获取键盘标准输入
键盘的输入内容为: Scanner sc = new Scanner(System.in);
键盘的输入内容为:
键盘的输入内容为: // 只把回车作为分隔符
键盘的输入内容为: sc.useDelimiter("\n");
键盘的输入内容为:
键盘的输入内容为: // 判断是否还有下一个输入项
键盘的输入内容为: while (sc.hasNext()) {
键盘的输入内容为: // 输出输入项
键盘的输入内容为: System.out.println("键盘的输入内容为:" + sc.next());
键盘的输入内容为: }
键盘的输入内容为:
键盘的输入内容为: } catch (IOException ioe) {
键盘的输入内容为: ioe.printStackTrace();
键盘的输入内容为: }
键盘的输入内容为:
键盘的输入内容为: }
键盘的输入内容为:
键盘的输入内容为:}