java IO流(四)--重定向标准输入输出

这是今天看到一个分类,值得看一下,我就先收藏在这了:
这里写图片描述

下面我们来讲重定向标准输入输出:

前面介绍过,标准输入输(System.in,System.out)出就是键盘输入和显示屏输出(也是eclipse控制台输出),在System类还提供了三个重定向标准输入输出的方法:

static void setErr(PrintStream err) //重定向标准错误输出流

static void setIn(InputStream in) //重定向标准输入流

static void setOut(PrintStream err) //重定向标准输出流

例1:重定向标准输出流

public static void main(String[] args) throws IOException{
        PrintStream ps=new PrintStream(new FileOutputStream("out.txt"));
        PrintStream out = System.out;//如果想重定向回标准输出,必须提前保存标准输出,如果这句话放在setOut后面会无效
        System.setOut(ps);//将标准输出流重定向到ps输出流
        System.out.println("输入到文件");
        System.setOut(out);
        System.out.println("输入到控制台");
}

例2:重定向标准输入

public static void main(String[] args) throws IOException{
        //将标准输入重定向到fis输入流
        FileInputStream fis=new FileInputStream("in.txt");
        System.setIn(fis);
        Scanner sc=new Scanner(System.in);
        String str=sc.nextLine();
        System.out.println("你输入内容:"+str);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值