Java的简单理解(24)---打印流 (PrintStream)

Java

打印流 (PrintStream)

/**
 * PrintStream ---> 打印流
 */
public void test1() throws FileNotFoundException {
    System.out.println("test");
    PrintStream ps = System.out;
    ps.println(false);

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

    ps.close();
}
/**
 * 三个常量:
 *      1. System.in 输入流
 *      2. System.out 输出流
 *         System.err
 */
public void test2() {
    System.out.println("test");
    System.err.println("err");
}
public void test3() throws FileNotFoundException {
   InputStream is = System.in; // 键盘输入
   is = new FileInputStream("E:/xp/test/print.txt"); // 从文件输入,作为数据源
   Scanner sc = new Scanner(is);
// System.out.println("请输入:");
   System.out.println(sc.nextLine());
}
/**
 * 重定向
 */
public void test4() throws FileNotFoundException {
    // 输出重定向(输出到文件)
    System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("E:/xp/test/print.txt")),true));
    System.out.println("a");
    System.out.println("test");

    // 重定向到控制台
    System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out))));
    System.out.println("back...");
}
/**
 * 封装输入
 * @throws IOException
 */
public void test5() throws IOException {
    InputStream is = System.in;
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    System.out.println("请输入...");
    String msg = br.readLine();
    System.out.println(msg);
}

你可能感兴趣的:(Java的简单理解(24)---打印流 (PrintStream))