IO分類:
按照數據流向分類:
輸入流
輸出流
按照處理的單位划分:
字節流:字節流讀取的都是文件中的二進制數據,讀取到的二進制數據不會經過任何處理
字符流:字符流讀取的數據都是以字符為單位的,字符流也是讀取的文件的二進制數據,只不過會把這些二進制數據轉換成我們能識別的字符
字符流 = 字節流 + 解碼
輸出字節流::
------------------|OutputStream 所有輸出字節流的基類 抽象類
-----------|FileOutputStream 向文件輸出數據的輸出字節流 throws FileNotFoundException
FileOutputStream的使用步驟:
1.找到目標文件
2.建立數據通道
3.把數據轉換成字節數組寫出
4.關閉資源
FileOutputStream的一些方法:
close() 關閉此文件輸出流並釋放與此流有關的所有系統資源。
write(int b) 將指定字節寫入此文件輸出流。
write(byte[] b) 將 b.length 個字節從指定 byte 數組寫入此文件輸出流中。
write(byte[] b, int off, int len) 將指定 byte 數組中從偏移量 off 開始的 len 個字節寫入此文件輸出流。
注意:
1.write(byte b[])方法實際上是調用了 write(byte b[], int off, int len)方法
FileOutputStream要注意的細節:
1.使用FileOutputStream的時候,如果目標文件不存在,那么會創建目標文件對象,然后把數據寫入
2.使用FileOutputStream的時候,如果目標文件已經存在,那么會清空目標文件的數據后再寫入數據,如果需要再原數據的上追加數據,需要使用FileOutputStream(file,true)構造函數
3.使用FileOutputStream的write方法寫數據的時候,雖然接受的是一個int類型的數據,但真正寫出的只是一個字節的數據,只是把低八位的二進制數據寫出,其他二十四位數據全部丟棄
public class Demo2 { public static void main(String[] args) { //1.找到目標文件 File file = new File("D:\\新建文件夾 (2)\\a.txt"); System.out.println("文件的源文數據是:"+readFile(file)); writeFile(file,"Hello World!"); System.out.println("目前文件數據是:"+readFile(file)); } //輸出數據 public static void writeFile(File file,String data) { FileOutputStream fileOutputStream = null; try{ //2.建立通道(我的源文件數據:abc 追加數據) fileOutputStream = new FileOutputStream(file,true); //3.把要寫入的數據轉換成字符數組 fileOutputStream.write(data.getBytes()); }catch(IOException e) { throw new RuntimeException(e); }finally { //關閉資源 try { fileOutputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } //輸入數據 public static String readFile(File file) { FileInputStream fileInputStream = null; String str = ""; try { //建立數據通道 fileInputStream = new FileInputStream(file); //創建緩沖字節數組 byte[] buf = new byte[1024]; int length = 0; while((length = fileInputStream.read(buf))!=-1) { //把字節數組轉換成字符串返回 str+=new String(buf,0,length); } } catch (IOException e) { throw new RuntimeException(); }finally { try { fileInputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } return str; } }

