标准I/O

在程序运行时,会默认为我们打开三个流:标准输入流、标准输出流、标准出错流。

  • 标准输入流一般对应我们的键盘
  • 标准输出流一般对应显示器
  • 标准出错流一般也对应显示器

1.标准输入流


  在标准I/O中,java提供了System.in,System.out,System.err分别对应标准输入、标准输出和标准出错。因为System.out与System.err都是PrintStream对象,所以直接可以使用,而System.in是一个未经任何修饰的InputStream,这表明我们在使用System.in时需要对其进行包装。

package com.dy.xidian;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Scanf {
    
    public static void main(String[] args) throws IOException {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(
                System.in));
        String s;
        while ((s = stdin.readLine()) != null && !s.equals("n")) {
            System.out.println(s);
        }
    }
}

2.I/O重定向


 重定向,顾名思义就是重新确定输出方向。比如System.out是将内容输出到显示屏上,但我们可以通过重定向让其将内容输出到一个文本文件中去。重定向操作的是字节流,而不是字符流。

package com.dy.xidian;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;

public class Redirecting {
    public static void main(String[] args) throws IOException {
        // 获取标准输出(控制台)
        PrintStream console = System.out;
        // 打开文件的输入流
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(
                "E:/html/utf-8.php"));
        // 打开文件输出流
        PrintStream out = new PrintStream(new BufferedOutputStream(
                new FileOutputStream("test.out")));
        // 将标准输入流重定向到文件上
        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.close();
        // 重新定向到控制台
        System.setOut(console);
    }
}

 

原文地址:https://www.cnblogs.com/xidongyu/p/5400484.html