IO:重定向标准输入流

22 篇文章 0 订阅

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();

键盘的输入内容为:		}

键盘的输入内容为:

键盘的输入内容为:	}

键盘的输入内容为:

键盘的输入内容为:}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值