字節流通常以stream結尾,例如InputStream和OutputStream。記幾個語法。
1.誤區
以前總是以為Input就是輸入,寫入文件; Output就是輸出,讀出文件。這是錯誤的理解,以至於看不懂很多例子。
這里的入和出是以內存為角度的,程序運行在內存中,創建的數組就可以看作內存。
把文件里的東西弄入數組里就是Input;把數組里的東西弄出來,進文件就是Output。
所以Input是寫入內存,而不是寫入文件;Output是讀出內存,而不是讀出文件。
2.讀取文件
把文件內容 寫入 內存數組里,用的是Input。
//讀取文件 public static void test1() throws IOException{ //指定文件路徑 File file = new File("src/resources/data.txt"); //為讀取文件提供流通道 InputStream inputStream = new FileInputStream(file); //創建字節數組存儲數據 byte[] bytes = new byte[1024]; //讀取指定文件中的內容要bytes數組 inputStream.read(bytes);//把文件里的數據 讀入 內存數組bytes //關閉輸出流 inputStream.close(); //輸出bytes數組內容 System.out.println(new String(bytes)); }
效果是最后一行輸出data.txt中的數據。
3.寫入文件
把內存數組里的內容 讀出內存,放入文件。
//寫入文件 public static void test2() throws IOException { //指定文件路徑 File file = new File("src/resources/data2.txt"); //為寫入文件提供流通道 FileOutputStream outputStream = new FileOutputStream(file); //創建字節數組 byte[] bytes = "hello world".getBytes(); //將內存的字節數組內容 弄進 文件中 outputStream.write(bytes,0,bytes.length-1);//末尾長度-1后文件只獲取了"hello word" //關閉流 outputStream.close(); }
4.Channel管道
流只能單向傳輸,要么輸入要么輸出。
管道可以雙向,但必須經過緩沖區buffer。
這個多用於socket編程,現在記錄一下讀出文件,寫入內存的用法。
//Channel一個用法 public static void test3() throws IOException{ //指定文件路徑 File file2 = new File("src/resources/data2.txt"); FileOutputStream outputStream = new FileOutputStream(file2); //管道 連着 流 FileChannel channel2 = outputStream.getChannel(); //通過Channel的讀寫必須經過Buffer緩沖區 ByteBuffer buffer2 = ByteBuffer.allocate(1024); //把string的內容寫入data2文件 String string = "守林鳥 博客園"; buffer2.put(string.getBytes()); buffer2.flip();//此處必須要調用buffer的flip方法,具體原因自行百度 //再將內容放進管道,寫入文件 channel2.write(buffer2); //關閉 管道和流 channel2.close(); outputStream.close(); /** 文件 --- 流 --- 緩沖區 --- 管道 --- 文件 */ }
5.BufferedReader用法
BufferedReader用法,鍵盤輸入,效果和Scanner一樣
//BufferedReader用法,鍵盤輸入,效果和Scanner一樣 public static void test4() throws IOException { String string; BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); string = buf.readLine(); System.out.println(string); Scanner scan = new Scanner(System.in); string = scan.nextLine(); System.out.println(string); }