標籤:
1.IO流用來處理裝置之間的資料轉送
方向:硬碟通過“讀reader”完成對記憶體的讀取,記憶體通過“寫writer”完成對硬碟的寫入
2.Java對資料的操作是通過流的方式
3.Java用於操作流的對象都在IO包中
4.流按操作資料分為兩種:位元組流和字元流
--字元流的由來:
》》位元組流讀取文字位元組資料後,不直接操作而是先查指定的編碼錶。擷取對應的文字。再對這個文字進行操作。簡單說:字元流=位元組流+編碼錶
--位元組流的兩個頂層父類:1.InputStream 2.OutputStream
--字元流的兩個頂層父類:1.Reader 2.Writer
--字元流:
》》要操作文字資料,優先考慮字元流
》》而且要將資料從記憶體寫到硬碟上,要使用字元流中的輸出資料流。Writer
-操作檔案的關鍵字為FileWriter,用於寫入資料流。具體格式:FileWriter fw=new FileWriter(“demo.txt”,true);這是目標檔案名,建立對象時會拋出個異常IOexception,這是因為檔案名稱或許沒有正確的路徑,會不安全。如果路徑檔案不存在,則自動建立,如果存在,則會覆蓋
小細節:在java裡實現換行操作可以用\r,或者用LINE_SEPARATOR建立變數,調用System方法
此處代碼
public class IOExceptionDemo { private static final String LINE_SEPARATOR = System.lineSeparator(); public static void main(String[] args) { FileWriter fw = null; try { fw = new FileWriter("demo.txt", true); fw.write("abcde" + LINE_SEPARATOR + "hahaha"); } catch (IOException e) { System.out.println(e.toString()); } finally { if (fw != null) try { fw.close(); } catch (IOException e) { throw new RuntimeException("關閉失敗"); } } }}
這是重點,FileWriter處理異常的方式!!很重要
讀取字元資料的關鍵字FileReader,具體格式 FileReader fr=new FileReader(“demo.txt”);必須保證檔案是存在的,再調用read方法讀取
read讀取方法有兩種方式:
public class Test11 { public static void main(String[] args) throws IOException { FileReader fr=new FileReader("demo.text"); int ch=fr.read(); System.out.println(ch); fr.close(); }}
這是方式一,挨個字元讀取檔案內的字元
public class Test11 { public static void main(String[] args) throws IOException { FileReader fr=new FileReader("demo.text"); char[] buf=new char[3]; int num=fr.read(buf);//將讀取到的字元儲存到數組中 System.out.println(num+" "+buf.toString()); int num1=fr.read(buf);//將讀取到的字元儲存到數組中 System.out.println(num+" "+buf.toString()); int num2=fr.read(buf);//將讀取到的字元儲存到數組中 System.out.println(num+" "+buf.toString()); }}
這是方式二,
兩者的區別是方式2可以一次讀取多個,方式1讀取1個字元。
方式2有個細節就是當數組定義為3個時,每次重新讀取的時候都放在同一個數組中,所以要覆蓋先前讀取的資料,然後輸出的結果會覆蓋,這個要注意!!!!
在這再說說複製的實現過程:
原理:讀取c盤檔案中的資料,然後再寫入d盤檔案中,連讀帶寫
5.流按流向分為:輸入資料流,輸出資料流
java基礎學習筆記之IO流