IO流操作與檔案File操作

來源:互聯網
上載者:User

      今天講解的是檔案操作File、FileFilter過濾器的介面和RandomAccessFile隨機讀寫操作。

一、    File類

a)      構造方法File(String path,String name); 構造方法參數可以儲存一個檔案名稱,可以只存一個檔案夾,也可以是絕對路徑可以是兩個,前者是路徑,後者是檔案名稱。也可以是File(File 目錄,String name)。

b)     靜態常量  separator 和separatorChar分別表示目錄之間的/ \\

c)      特有方法:getName() 返迴文件對象名。 getPath()返回對象中封裝的路徑。 getAbsolutPath()返回絕對路徑 getParent()返回父檔案對象的路徑名,如果是相對路徑,則返回為null

getParent()返回父檔案對象獲得檔案屬性 length()返迴文件自己長度 lastModfied() 返迴文件最後修改的時間 可以作為Data類的參數 delete()刪除目錄或者檔案。返回真假值 mkdir()建立目錄 list() 返回子目錄裡所有檔案的名字。 listFile()返回目錄中的所有檔案對象

      遞迴方法:public void listDir(File dir){

         System.out.println(dir.getName());

         File[] files=dir.listFiles();        

         for(int i=0;i<files.length;i++){

                   if(files[i].isFile())    //如果是檔案直接輸入

                            System.out.println(files[i].getName());

                   Else        //則向下個目錄

                            listDir(files[i]);

         }

二、    過濾器FileFilter介面

成員方法boolean accept(Filepathname)需要從寫內容。來實現過濾檔案的作用。大概可以這樣寫

//過濾邏輯條件

       if(pathname.isDirectory())

           return false;

       //不是目錄

       String filename=pathname.getName();

       int n=filename.indexOf(".");//找.的位置

       if(n==-1 || n==filename.length())//如果沒有找到或者在最後找到

           return false;

       if(filename.substring(n+1).equals(externName)){//從.分割字串與檔案尾碼對比。 這有漏洞 如果是以.txt.txt結束的則不能被通過。

           return true;

       }

      

       return false;

    }

三、    隨機檔案操作RandomAccessFile類可以對檔案進行隨機讀寫的功能

a)      構造方法 RandomAccessFile(File file,String mode);後面為模式 如”r”是只能讀 “w”是只能讀”rw”是能讀寫功能

b)      具體方法:readInt()   readDouble()等方法與WriteInt()同理。讀、寫UTF字串: readUTF()、writeUTF(Stringstr);readLine()方法

c)       getFilePointer() ---得到當前的檔案讀取指標seek(long pos) ---把指標從開始移動到pos位置  length()---得到檔案的長度(有多少個位元組) setLength(long newLength) 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.