Java编程思想:标准I/O

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;

import java.io.*;

public class Test {
    public static void main(String[] args) {
//        Echo.test();
//        ChangeSystemOut.test();
        Redirecting.test();
    }
}

class Echo {
    public static void test() {
        BufferedReader stdin = new BufferedReader(
                new InputStreamReader(System.in));

        try{
            String s;
            while ((s = stdin.readLine()) != null&&s.length()!=0) {
                System.out.println(s);
            }
        } catch (IOException e) {
            //e.printStackTrace();
            throw new RuntimeException(e);
        }

    }
}

class ChangeSystemOut {
    public static void test() {
        PrintWriter out = new PrintWriter(System.out,true);
        out.println("Hello, world");
//        out.close();
    }
}

class Redirecting{
    public static void test() {
        try{
            PrintStream console = System.out;

            //创建输入流,用于重定向输入
            BufferedInputStream in = new BufferedInputStream(
                    new FileInputStream("./src/Test.java"));

            //创建输出流,用于重定向输出
            PrintStream out = new PrintStream(
                    new FileOutputStream("./src/out"));

            System.setIn(in);
            System.setOut(out);
            System.setErr(out);

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

            try{
                String str;
                while ((str = br.readLine()) != null) {
                    System.out.println(str);
                }
            }finally {
                br.close();
                out.close();
            }
            System.setOut(console);


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }

    }
}

猜你喜欢

转载自www.cnblogs.com/junjie2019/p/10537962.html
今日推荐