引用自:http://www.cnblogs.com/liunanjava/p/4307793.html
1.三个静态变量
java.lang.System提供了三个静态变量
- System.in(默认键盘)
- System.out(默认显示器)
- System.err
- System提供了三个重定向方法
2.重写向方法
System提供了三个重定向方法
方法 | 说明 |
static void setErr(PrintStream errr) | 重定向标准错误输出流 |
static void setIn(InputStream in ) | 重定向标准输入流 |
static void setOut(PrintStream out) | 重定向歀输出流 |
3.实例
重定向输入流
package com.pb.io.reio;import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException;/** 重定向输入* 1.有一个已经初始化的InputStream输入流* 2.调用System.setIn()方法,将标淮输入流重定向到目的输入流* 3.读取System.in中的内容*/ public class ReIn {public static void main(String[] args) throws UnsupportedEncodingException
{ try {//1.声明一个输入流FileInputStream fis=new FileInputStream("d:/test/s1.txt");//2.重定向 System.setIn(fis);//3.读取System.in标准输入流中的内容BufferedReader br=new BufferedReader(new InputStreamReader(System.in,"gb2312")); //设置字符编码//4.输出System.in中的内容String line=null;while((line=br.readLine())!=null){System.out.println(line);}//5.关闭流 br.close();fis.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} }
重定向输出流
package com.pb.io.reio;import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream;/** 重定向标淮输出流* 1.初始化PrintStream对象* 2.调用System.setOut()方法,将标淮输出流重定向至PrintStream对象* 3.操作System.out流,*/ public class ReOut {public static void main(String[] args) {try {//1.声明一个输出流PrintStream对象PrintStream ps=new PrintStream(new FileOutputStream("d:/test/ps.txt",true)); //追加内容//2.重定向标淮输出流 System.setOut(ps);//3.使用PrintStream对象向流中写信息System.out.println("测试重定向成功了没有!");System.out.println(new ReOut());ps.close();} catch (FileNotFoundException e) {e.printStackTrace();} } }