Java的IO操作(一) – File類,RandomAccessFile類,FileInputStream、FileOutputStream類

來源:互聯網
上載者:User

在Java中,所有的輸入、輸出問題都會被抽象成流(Stream)對象來解決。下面介紹一下常用的輸入、輸出資料流對象的使用方法。

1、 File類

File類是檔案的抽象代表。一個檔案(包括目錄)就是一個File類的執行個體。java.io.File類為我們提供了一個抽象的、系統獨立的檔案表示,我們不必糾結於因為不同的作業系統檔案路徑的表示方法不同而造成的差異,File會將傳進去的路徑自動轉換為與系統無關的抽象路徑表示。File必須配合其它相關的類來使用。

2、 RandomAccessFile類

RandomAccessFile允許我們在檔案的任何位置執行讀寫操作,我們可以使用它的seek()方法來指定檔案讀寫的位置,類似於C語言中的feek()設定檔案指標。

例如,我們將3個學生資訊(姓名,分數)寫入到檔案中,然後再從該檔案中讀取資料顯示到控制台上。使用者可以指定要從檔案中讀取第幾個學生的資訊:

package cls;import java.io.*;import java.util.Scanner;class Student // 學生類{    private String name;    private int score;        public Student(String name,int score)    {                StringBuilder buf = new StringBuilder(name);        buf.setLength(15); // 把每個name設定為15個字元長度                this.name = buf.toString();        this.score = score;    }    // 返回姓名    public String getName()    {        return name.toString();    }    // 返回分數    public int getScore()    {        return score;    }        public static void main(String[] args)    {        Student[] st = new Student[]{new Student("apple",100),new Student("dog",200),new Student("cat",300)};                        // 寫入資料        try        {            File file = new File(args[0]); //從命令列參數中指定檔案名稱                        RandomAccessFile raf = new RandomAccessFile(file,"rw"); //以可讀可寫的方式開啟流            for(int i = 0 ; i < st.length ; ++i)            {                raf.writeChars(st[i].getName()); // 寫入姓名                raf.writeInt(st[i].getScore()); // 寫入一個整形資料,即分數            }            raf.close();        }        catch(IOException e)        {             e.printStackTrace();        }                // 從檔案中讀取資料        try        {            File file = new File(args[0]);                        RandomAccessFile raf = new RandomAccessFile(file,"rw");//以可讀可寫的方式開啟流                        // 使用者指定要讀取第幾個學生的資訊            int pos;            Scanner sc = new Scanner(System.in);            pos = sc.nextInt();                        // 讀取第pos個學生的資訊            char[] buf = new char[15];            raf.seek((pos - 1) * 34); // 設定讀取位置,對於每個學生資訊我們分別寫入了34個位元組                       //讀取資料            for(int i = 0 ; i < buf.length ; ++i)                buf[i] = raf.readChar(); // 一個字元一個字元地讀取            String str = new String(buf);                        // 顯示資料            System.out.println(str.replace('\0',' ')); // 把buf中的\0全部替換成 空格            System.out.println(raf.readInt());                        raf.close();        }        catch(IOException e)        {             e.printStackTrace();        }            }}

我們可以通過執行 

java cls.Student temp.dat

來指定要把學生資料儲存到temp.dat檔案中。

程式中輸入序號N就能從檔案中直接讀取第N個學生的資料。

但是在讀取的時候有一點需要注意,自己一定要清楚一個學生資訊的資料區塊佔多少個位元組,否則讀取資料時就會亂套了。。

3、抽象類別InputStream和OutputStream

InputStream類是所有表示位輸入資料流的類的父類,例如System.in就是它的一個對象。OutputStream是所有表示位輸出資料流的類的父類,如System.out就間接繼承了OutputStream類。我們可以使用System.in對象來從鍵盤中讀入一個字元的資料,讀入的資料會以int類型返回(int佔4個位元組,其中只有最後一個位元組是有效資料)。下面的小程式示範了System.in的使用方法 :

package cls;public class StreamDemo{    public static void main(String[] args) throws Exception    {        System.out.println("You just inputed : " + System.in.read());    }}

4、FileInputStream和FileOutputStream

這兩個類分別是InputStream和OutputStream的子類。因此它實現了抽象父類中的所有方法。顧名思義,它們的功能是從指定檔案中執行讀寫操作。我們可以模仿windows命令提示字元中的copy命令,自己去寫一個山寨版的 copy。

我們從命令列參數中讀入源檔案、目標檔案,然後利用read()方法,write()方法即可完成檔案的拷貝。

我們定義一個大小為 5MB的 位元組資料來作為緩衝區,以達到提高讀寫效率的目的。詳見代碼:

package cls;import java.io.*;public class FileStreamDemo{    public static void main(String[] args)    {        try        {            // 源檔案            File fSource = new File(args[0]);            try            {                // 目地檔案                File fDest = new File(args[1]);                                // 建立流                FileInputStream fis = new FileInputStream(fSource);                FileOutputStream fos = new FileOutputStream(fDest);                                try                {                    // 緩衝區                    byte[] buf = new byte[1024 * 1024 * 5];                                        // 拷貝資料                    while(true)                    {                        int res = 0;                        long size = fis.available(); // 擷取源檔案大小                                                // 從源檔案中讀取資料,再寫入至目標檔案中                        if(size < 1024 * 1024 * 5)                        {                            fis.read(buf);                            fos.write(buf,0,size);                            System.out.println("Buffered output!");                        }                        else                        {                            while((res = fis.read()) != -1)                            {                                fos.write(res);                            }                        }                        break;                    }                    // 關閉流                    fis.close();                    fos.close();                    System.out.println("Copy finish");                     }                catch(Exception e)                {                     e.printStackTrace();                }            }            catch(Exception e)            {                 System.out.println("Please input the aim file!");                 System.exit(0);            }        }        catch(Exception e)        {             System.out.println("Please input the source file!");             System.exit(0);        }    }}

經過測試,如果不使用緩衝資料,那麼拷貝檔案的操作是非常之慢的,慢到能讓人砸電腦。。由此可見從硬碟等外部存放裝置中讀取資料要遠遠慢於從記憶體中讀取(廢話。。)。以上面的程式為例,如果要拷貝的檔案在5M以內,那麼整個拷貝過程完全可以秒過。反之,那就悲劇了。。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.