IO流


一、IO流的三種分類方式

      1.按流的方向分爲:輸入流和輸出流

      2.按流的數據單位不同分爲:字節流和字符流

      3.按流的功能不同分爲:節點流和處理流

    二、IO流的四大抽象類:

       字符流:Reader Writer

       字節流:InputStream(讀數據)

       OutputStream(寫數據)

    三、InputStream的基本方法

         int read() throws IOException 讀取一個字節以整數形式返回,如果返回-1已到輸入流的末尾

        void close() throws IOException 關閉流釋放內存資源

        long skip(long n) throws IOException 跳過n個字節不讀

    四、OutputStream的基本方法

       void write(int b) throws IOException 向輸出流寫入一個字節數據

       void flush() throws IOException 將輸出流中緩衝的數據全部寫出到目的地

    五、Writer的基本方法

       void write(int c) throws IOException 向輸出流寫入一個字符數據

       void write(String str) throws IOException將一個字符串中的字符寫入到輸出流

       void write(String str,int offset,int length)

       將一個字符串從offset開始的length個字符寫入到輸出流

       void flush() throws IOException

       將輸出流中緩衝的數據全部寫出到目的地

    六、Reader的基本方法

       int read() throws IOException 讀取一個字符以整數形式返回,如果返回-1已到輸入流的末尾

      Java.io 包提供了 RandomAccessFile 類用於隨機文件的創建和訪問。使用這個類,可以跳轉到文件的任意位置讀寫數據。程序可以在隨機文件中插 入數據,而不會破壞該文件的其他數據。此外,程序也可以更新或刪除先前存儲的數據,而不用重寫整個文件。

     

import java.io.*;  
public class TestRandom{  
    public static void main(String args[]) throws IOException{  
        try{  
            BufferedReader in=new BufferedReader(new InputStreamReader(System.in));  
            String s=in.readLine();  
            RandomAccessFile myFile=new RandomAccessFile("f:\\java\\TestRandom.log","rw");  
            myFile.seek(myFile.length());  //移動到文件結尾  
            myFile.writeBytes(s+"\n");  //寫入數據  
            myFile.close();  
        }  
        catch(IOException e){}  
    }  
}  

             程序運行後在目錄中建立一個 TestRandom.log 的文件,每次運行時輸入的內容都會在該文件內容的結尾處添加。

                  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章