JavaSE:RandomAccessFile 類

RandomAccessFile 類java

  1.  基本概念dom

        java.io.RandomAccessFile類:支持對隨機訪問文件的讀寫操做ide

  2.  經常使用的方法指針

        方法聲明                                    功能介紹對象

        RandomAccessFile(String name,String mode)                    根據參數指定的名稱和模式構造對象blog

                                                 r:以只讀方式打開資源

                                                 rw: 打開一遍讀取和寫入同步

                                                 rwd:打開以便讀取和寫入,同步文件內容的更新it

                                                 rws: 打開以便讀取和寫入,同步文件內容和元數據的更新io

        int read()                                    讀取單個字節的數據

        void seek(long pos)                                用於設置今後文件的開頭開始測量的文件指針偏移量

        void write(int b)                                  將參數指定的單個字節寫入

        void close()                                     用於關閉流並釋放有關的資源

  3.  代碼示例

      class RandomAccessFileTest {

        main(String[] args){

          RandomAccessFile raf = null;

          try{

            //  1. 建立RandomAccessFile類型的對象,與d:/a.txt文件關聯

            raf = new RandomAccessFile("d:/a.txt","rw");

            //  2. 對文件內容進行隨機讀寫操做

            //  設置距離文件開頭位置的偏移量,從文件開頭位置向後偏移3個字節  aellhello

            raf.seek(3);

            int res = raf.read();

            System.out.println("讀取到的單個字符是:" + (char)res); // a l
            res = raf.read();
            System.out.println("讀取到的單個字符是:" + (char)res); // h 指向了e
            raf.write('2'); // 執行該行代碼後覆蓋了字符'e'
            System.out.println("寫入數據成功!");

            } catch (IOException e) {
              e.printStackTrace();
            } finally {
              // 3.關閉流對象並釋放有關的資源
              if (null != raf) {
                try {
                  raf.close();
                } catch (IOException e) {
                  e.printStackTrace();
                }
              }
            }

          }

        }

      } 

 

4.  IO流練習

相關文章
相關標籤/搜索