案例 1-6: 重定向标准输出设备

来源:互联网 发布:淘宝可靠的泰国代购 编辑:程序博客网 时间:2024/04/29 09:19

 /*
 * 案例 1-6: 重定向标准输出设备
 * 目标: 掌握重定向标准输出设备的方法, 并由此掌握重定向标准输入设备的方法
 */
import java.io.*;

public class Redirection {

 public static void main(String[] args) {
  FileOutputStream fos = null;
  PrintStream ps = null;
  try {
   // 建立一个文件输出流, 并将它的 append 标记设置为 true
   fos = new FileOutputStream("system.txt", true); // 1
   // 建立了一个 PrintStream 对象, 它将作为 标准输出流
   ps = new PrintStream(fos); // 2
   // 将标准输出定向到 PrintStream 对象
   System.setOut(ps); // 3
   // 输出一条数据, 它不再会在控制台输出
   // 而是输出到了文件 system.txt 中
   System.out
     .println("This string will be written into the file 'system.txt'");// 4

  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    fos.close();
    ps.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }

 }
 /*
  * 若想将 System.in 和 System.out 流重定向 到其他的设备上, 需要首先创建一个封装源 System.in 或
  * System.out 的新流. 在这个例子中, 首先在 // 1 处 创建了一个 FileOutputStream 对象,然后将这个对象作为
  * PrintStream 构造器的参数 创建了一个 PrintStream 对象, 这个对象将作为新的 System.out 的设备,然后在 //
  * 3 处 使用 System 类的静态方法 setOut() 来重定向 System.out, 执行这个方法后, 在这个程序中 通过
  * System.out.print()/System.out.println() 输出的所有的数据将不会再控制台上显示, 而是会写入到文件
  * system.txt 中.
  *
  */
}

原创粉丝点击