Java学习笔记之--------IO流之打印流

打印流

三个常量:

1.System.in 输入流

2.System.out 输出流:调试代码,打印日志

3.System.err 打印出的颜色是红色的

 重定向

setIn()

setOut()

setErr()

 下面为Demo:

public class PrintStreamDemo01 {

    public static void main(String[] args) throws FileNotFoundException {

        System.out.println("test");
        PrintStream ps = System.out;
        ps.println(false);

        //输出到文件
        File src = new File("d:/xp/test/print.txt");
        ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(src)));
        ps.print("io is so easy ...");
        ps.close();
    }

}

我们可以看到文件如下:

然后我们看下面的代码:

public class SystemDemo01 {

    public static void main(String[] args) throws FileNotFoundException {
        //test1();
        //test2();
        //重定向
        System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("d:/xp/test/system.txt")), true));
        System.out.println("a");  //从控制台转向文件
        //回控制台
        System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)),true));
        System.out.println("bank...");
    }

    //文件输入
    public static void test2() throws FileNotFoundException {
        InputStream is = System.in;
        is = new BufferedInputStream(new FileInputStream("d:/xp/test/print.txt"));
        Scanner sc = new Scanner(is);
        System.out.println(sc.nextLine());
    }

    public static void test1(){
        System.out.println("test");
        System.err.println("err");
    }
}

test1的执行结果为:

我们可以看到,System.err打印到控制台的日志是红色的,也就是我们平时看到的报错日志。

test2的执行结果如下:

可以看到,PrintStreamDemo01中输入到print.txt文件中的内容被打印输出到了控制台。

然后main方法中的代码执行结果如下:

重定向之后 ,我们就可以看到system.txt文件中内容如下:

在回控制台之后,输出的内容就会输出到控制台。

以上为打印流的Demo以及运行结果。

猜你喜欢

转载自blog.csdn.net/wangruoao/article/details/83995422
今日推荐