1 import java.io.FileWriter; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4
5 /*
6 * 需求:從鍵盤讀入一些字符,並寫入的項目根目錄下的file.txt文件當中 7 * 8 * 用到的類:InputStreamReader FileWriter System.in 9 * InputStreamReader的作用:將字節轉換成字符, 可以指定字符集 10 */
11 public class InputStreamReaderDemo { 12
13 public static void main(String[] args) throws IOException { 14 //創建輸入流對象
15 InputStreamReader is = new InputStreamReader(System.in); 16
17 //創建輸出流對象
18 FileWriter os = new FileWriter("file.txt"); 19
20 //讀寫數據
21 int len = 0; //記錄每次讀到字符數組的長度
22 char[] str = new char[1024]; 23 while ((len = is.read(str)) != -1) { 24 os.write(str, 0, len); 25 os.flush(); 26 } 27
28 //釋放資源
29 is.close(); 30 os.close(); 31 } 32 }