Java 标准I/O重定向

转载请标明出处:http://blog.csdn.net/xx326664162/article/details/51690162 文章出自:薛瑄的博客

你也可以查看我的其他同类文章,也会让你有一定的收货!

Java的标准输入/输出分别通过System.in和System.out来代表,在默认的情况下分别代表键盘和显示器

  • 当程序通过System.in来获得输入时,实际上是通过键盘获得输入。
  • 当程序通过System.out执行输出时,程序总是输出到屏幕

在System类中提供了三个重定向标准输入/输出的方法
static void setErr(PrintStream err) 重定向“标准”错误输出流
static void setIn(InputStream in) 重定向“标准”输入流
static void setOut(PrintStream out)重定向“标准”输出流

下面程序通过重定向标准输出流:

将System.in的输入重定向到文件上,而不是在键盘上输入。
将System.out的输出重定向到文件输出,而不是在屏幕上输出。

package com.example;//: io/Redirecting.java
// Demonstrates standard I/O redirection.

import java.io.*;

public class Redirecting {
    public static void main(String[] args)
            throws IOException {
        PrintStream console = System.out;
        BufferedInputStream in = new BufferedInputStream(
                new FileInputStream("Redirecting.java"));
        PrintStream out = new PrintStream(
                new BufferedOutputStream(
                        new FileOutputStream("test123.txt")));

        System.setIn(in);
        System.setOut(out);
        System.setErr(out);
        BufferedReader br = new BufferedReader(
                new InputStreamReader(System.in));
        String s;
        while ((s = br.readLine()) != null)
            System.out.println(s);
//           如果不使用重定向,使用下面的语句,也可达将内容写到指定文件中
//            out.println(s);
        out.close(); // Remember this!
        System.setOut(console);
    }
} ///:~

在第14行的test123.txt,会输出到与项目同级的目录中

转载:http://blog.csdn.net/zhy_cheng/article/details/7891142

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值