java中重定向标准IO

来源:互联网 发布:淘宝联盟网站推广设置 编辑:程序博客网 时间:2024/06/08 05:15
1.  3个重定向方法    System类提供了3个重定向输入输出方法:    1)static void setErr(PrintStream err):重定向“标准“错误输出流。    2)static void setIn(InputStream in):重定向”标准“输入流。    3)static void setOut(PrintStream out):重定向”标准“输出流。[java] view plain copyimport java.io.*;  import java.util.*;  class RedirectInOut  {      public static void main(String[] args)       {          try(PrintStream ps=new PrintStream(new FileOutputStream("out.txt"));//重定向标准输出为"out.txt"              FileInputStream fis=new FileInputStream("RedirectInOut.java")//重定向标准输入为"RedirectInOut.java"文件              )          {              System.setOut(ps);              System.out.println("这是一个重定向输出");              System.setIn(fis);              Scanner sc=new Scanner(System.in);              sc.useDelimiter("\n");              System.out.println("重定向输入内容:");              while(sc.hasNext())              {//将"RedirectInOut.java"文件的内容写入"out.txt"文件                  System.out.println(sc.next());              }          }          catch(IOException ex)          {              ex.printStackTrace();          }      }  }