Java IO转换流-需求演示

1,需求:将键盘录入的数据写入到一个文件中。

2,需求:将一个文本文件内容显示在控制台上。

 

例:TransStreamTest.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class TransStreamTest {
   public static void main(String[] args) throws IOException {
      method_2();
   }

   // 1, 需求:将键盘录入的数据写入到一个文件中。
   public static void method_1() throws FileNotFoundException, IOException {
      BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
      BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\1.txt")));
      String line = null;
      while ((line = bufr.readLine()) != null) {
         if (line.equals("over"))
            break;
         bufw.write(line);
         bufw.newLine();
         bufw.flush();
      }
   }

   // 2, 需求:将一个文本文件内容显示在控制台上。
   public static void method_2() throws FileNotFoundException, IOException {
      BufferedReader bufr = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\demo.txt")));
      BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out));
      String line = null;
      while ((line = bufr.readLine()) != null) {
         if (line.equals("over"))
            break;
         bufw.write(line);
         bufw.newLine();
         bufw.flush();
      }
   }
}