一、概述
1、Java IO
? ? ? ?Java IO即Java 輸入輸出系統。不管我們編寫何種應用,都難免和各種輸入輸出相關的媒介打交道,其實和媒介進行IO的過程是十分復雜的,這要考慮的因素特別多,比如我們要考慮和哪種媒介進行IO(文件、控制臺、網絡),我們還要考慮具體和它們的通信方式(順序、隨機、二進制、按字符、按字、按行等等)。Java類庫的設計者通過設計大量的類來攻克這些難題,這些類就位于java.io包中。
? ? ? ?在JDK1.4之后,為了提高Java IO的效率,Java又提供了一套新的IO,Java New IO簡稱Java NIO。它在標準java代碼中提供了高速的面向塊的IO操作。本篇文章重點介紹Java IO,關于Java NIO請參考我的另兩篇文章:
Java NIO詳解(一)?
Java NIO詳解(二)
2、流
? ? ? ?在Java IO中,流是一個核心的概念。流從概念上來說是一個連續的數據流。你既可以從流中讀取數據,也可以往流中寫數據。流與數據源或者數據流向的媒介相關聯。在Java IO中流既可以是字節流(以字節為單位進行讀寫),也可以是字符流(以字符為單位進行讀寫)。
3、IO相關的媒介
Java的IO包主要關注的是從原始數據源的讀取以及輸出原始數據到目標媒介。以下是最典型的數據源和目標媒介:
- 文件
- 管道
- 網絡連接
- 內存緩存
- System.in, System.out, System.error(注:Java標準輸入、輸出、錯誤輸出)
二、Java IO類庫的框架
1、Java IO的類型
雖然java IO類庫龐大,但總體來說其框架還是很清楚的。從是讀媒介還是寫媒介的維度看,Java IO可以分為:
? ? ? ?1)輸入流:InputStream和Reader
? ? ? ?2)輸出流:OutputStream和Writer
而從其處理流的類型的維度上看,Java IO又可以分為:
? ? ? ?1)字節流:InputStream和OutputStream
? ? ? ?2)字符流:Reader和Writer
下面這幅圖就清晰的描述了JavaIO的分類:
? | 字節流 | 字符流 |
---|---|---|
輸入流 | InputStream | Reader |
輸出流 | OutputStream | Writer |
? ? ? ?我們的程序需要通過InputStream或Reader從數據源讀取數據,然后用OutputStream或者Writer將數據寫入到目標媒介中。其中,InputStream和Reader與數據源相關聯,OutputStream和writer與目標媒介相關聯。 以下的圖說明了這一點:
2、IO類庫
? ? ? ?上面我們介紹了Java IO中的四各類:InputStream、OutputStream、Reader、Writer,其實在我們的實際應用中,我們用到的一般是它們的子類,之所以設計這么多子類,目的就是讓每一個類都負責不同的功能,以方便我們開發各種應用。各類用途匯總如下:
- 文件訪問
- 網絡訪問
- 內存緩存訪問
- 線程內部通信(管道)
- 緩沖
- 過濾
- 解析
- 讀寫文本 (Readers / Writers)
- 讀寫基本類型數據 (long, int etc.)
- 讀寫對象
下面我們就通過兩張圖來大體了解一下這些類的繼承關系及其作用
圖1:java io 類的集成關系
圖2:java io中各個類所負責的媒介
三、Java IO的基本用法
1、Java IO:字節流
? ? ? ?通過上面的介紹我們已經知道,字節流對應的類應該是InputStream和OutputStream,而在我們實際開發中,我們應該根據不同的媒介類型選用相應的子類來處理。下面我們就用字節流來操作文件媒介:
例1,用字節流寫文件
public static void writeByteToFile() throws IOException{String hello= new String( "hello word!");byte[] byteArray= hello.getBytes();File file= new File( "d:/test.txt");//因為是用字節流來寫媒介,所以對應的是OutputStream //又因為媒介對象是文件,所以用到子類是FileOutputStreamOutputStream os= new FileOutputStream( file);os.write( byteArray);os.close();}
例2,用字節流讀文件
public static void readByteFromFile() throws IOException{File file= new File( "d:/test.txt");byte[] byteArray= new byte[( int) file.length()];//因為是用字節流來讀媒介,所以對應的是InputStream//又因為媒介對象是文件,所以用到子類是FileInputStreamInputStream is= new FileInputStream( file);int size= is.read( byteArray);System. out.println( "大小:"+size +";內容:" +new String(byteArray));is.close();}
2、Java IO:字符流
? ? ? ?同樣,字符流對應的類應該是Reader和Writer。下面我們就用字符流來操作文件媒介:
例3,用字符流讀文件
public static void writeCharToFile() throws IOException{String hello= new String( "hello word!");File file= new File( "d:/test.txt");//因為是用字符流來讀媒介,所以對應的是Writer,又因為媒介對象是文件,所以用到子類是FileWriterWriter os= new FileWriter( file);os.write( hello);os.close();}
例4,用字符流寫文件
public static void readCharFromFile() throws IOException{File file= new File( "d:/test.txt");//因為是用字符流來讀媒介,所以對應的是Reader//又因為媒介對象是文件,所以用到子類是FileReaderReader reader= new FileReader( file);char [] byteArray= new char[( int) file.length()];int size= reader.read( byteArray);System. out.println( "大小:"+size +";內容:" +new String(byteArray));reader.close();}
3、Java IO :字節流轉換為字符流
? ? ? ?字節流可以轉換成字符流,java.io包中提供的 InputStreamReader類就可以實現,當然從其命名上就可以看出它的作用。其實這涉及到另一個概念,IO流的 組合,后面我們詳細介紹。下面看一個簡單的例子:
例5 ,字節流轉換為字符流
public static void convertByteToChar() throws IOException{File file= new File( "d:/test.txt");//獲得一個字節流InputStream is= new FileInputStream( file);//把字節流轉換為字符流,其實就是把字符流和字節流組合的結果。Reader reader= new InputStreamReader( is);char [] byteArray= new char[( int) file.length()];int size= reader.read( byteArray);System. out.println( "大小:"+size +";內容:" +new String(byteArray));is.close();reader.close();}
4、Java IO :IO類的組合
? ? ? ?從上面字節流轉換成字符流的例子中我們知道了IO流之間可以組合(或稱嵌套),其實組合的目的很簡單,就是把多種類的特性融合在一起以實現更多的功能。組合使用的方式很簡單,通過把一個流放入另一個流的構造器中即可實現,兩個流之間可以組合,三個或者更多流之間也可組合到一起。當然,并不是任意流之間都可以組合。關于組合就不過多介紹了,后面的例子中有很多都用到了組合,大家好好體會即可。
5、Java IO:文件媒介操作
? ? ? ?File是Java IO中最常用的讀寫媒介,那么我們在這里就對文件再做進一步介紹。
1)File媒介
例6 ,File操作
public class FileDemo {public static void main(String[] args) {//檢查文件是否存在File file = new File( "d:/test.txt");boolean fileExists = file.exists();System. out.println( fileExists);//創建文件目錄,若父目錄不存在則返回falseFile file2 = new File( "d:/fatherDir/subDir");boolean dirCreated = file2.mkdir();System. out.println( dirCreated);//創建文件目錄,若父目錄不存則連同父目錄一起創建File file3 = new File( "d:/fatherDir/subDir2");boolean dirCreated2 = file3.mkdirs();System. out.println( dirCreated2);File file4= new File( "d:/test.txt");//判斷長度long length = file4.length();//重命名文件boolean isRenamed = file4.renameTo( new File("d:/test2.txt"));//刪除文件boolean isDeleted = file4.delete();File file5= new File( "d:/fatherDir/subDir");//是否是目錄boolean isDirectory = file5.isDirectory();//列出文件名String[] fileNames = file5.list();//列出目錄File[] files = file4.listFiles();}
}
? ? ? ?通過上面的例子我們已經知道,我們可以用FileInputStream(文件字符流)或FileReader(文件字節流)來讀文件,這兩個類可以讓我們分別以字符和字節的方式來讀取文件內容,但是它們都有一個不足之處,就是只能從文件頭開始讀,然后讀到文件結束。
? ? ? ?但是有時候我們只希望讀取文件的一部分,或者是說隨機的讀取文件,那么我們就可以利用RandomAccessFile。RandomAccessFile提供了seek()方法,用來定位將要讀寫文件的指針位置,我們也可以通過調用getFilePointer()方法來獲取當前指針的位置,具體看下面的例子:
例7,隨機讀取文件
public static void randomAccessFileRead() throws IOException {// 創建一個RandomAccessFile對象RandomAccessFile file = new RandomAccessFile( "d:/test.txt", "rw");// 通過seek方法來移動讀寫位置的指針file.seek(10);// 獲取當前指針long pointerBegin = file.getFilePointer();// 從當前指針開始讀byte[] contents = new byte[1024];file.read( contents);long pointerEnd = file.getFilePointer();System. out.println( "pointerBegin:" + pointerBegin + "\n" + "pointerEnd:" + pointerEnd + "\n" + new String(contents));file.close();}
public static void randomAccessFileWrite() throws IOException {// 創建一個RandomAccessFile對象RandomAccessFile file = new RandomAccessFile( "d:/test.txt", "rw");// 通過seek方法來移動讀寫位置的指針file.seek(10);// 獲取當前指針long pointerBegin = file.getFilePointer();// 從當前指針位置開始寫file.write( "HELLO WORD".getBytes());long pointerEnd = file.getFilePointer();System. out.println( "pointerBegin:" + pointerBegin + "\n" + "pointerEnd:" + pointerEnd + "\n" );file.close();}
6、Java IO:管道媒介
? ? ? ?管道主要用來實現同一個虛擬機中的兩個線程進行交流。因此,一個管道既可以作為數據源媒介也可作為目標媒介。? ? ? ?需要注意的是java中的管道和Unix/Linux中的管道含義并不一樣,在Unix/Linux中管道可以作為兩個位于不同空間進程通信的媒介,而在java中,管道只能為同一個JVM進程中的不同線程進行通信。和管道相關的IO類為: PipedInputStream和 PipedOutputStream,下面我們來看一個例子:
例9,讀寫管道
public class PipeExample {public static void main(String[] args) throws IOException {final PipedOutputStream output = new PipedOutputStream();final PipedInputStream input = new PipedInputStream(output);Thread thread1 = new Thread( new Runnable() {@Overridepublic void run() {try {output.write( "Hello world, pipe!".getBytes());} catch (IOException e) {}}});Thread thread2 = new Thread( new Runnable() {@Overridepublic void run() {try {int data = input.read();while( data != -1){System. out.print(( char) data);data = input.read();}} catch (IOException e) {} finally{try {input.close();} catch (IOException e) {e.printStackTrace();}}}});thread1.start();thread2.start();}
}
? ? ? ?關于Java IO面向網絡媒介的操作即Java 網絡編程,其核心是Socket,同磁盤操作一樣,java網絡編程對應著兩套API,即Java IO和Java NIO,關于這部分我會準備專門的文章進行介紹。
8、Java IO:BufferedInputStream和BufferedOutputStream
? ? ? ?BufferedInputStream顧名思義,就是在對流進行寫入時提供一個buffer來提高IO效率。在進行磁盤或網絡IO時,原始的InputStream對數據讀取的過程都是一個字節一個字節操作的,而BufferedInputStream在其內部提供了一個buffer,在讀數據時,會一次讀取一大塊數據到buffer中,這樣比單字節的操作效率要高的多,特別是進程磁盤IO和對大量數據進行讀寫的時候。
? ? ? ?使用BufferedInputStream十分簡單,只要把普通的輸入流和BufferedInputStream組合到一起即可。我們把上面的例2改造成用BufferedInputStream進行讀文件,請看下面例子:
例10 ,用緩沖流讀文件
public static void readByBufferedInputStream() throws IOException {File file = new File( "d:/test.txt");byte[] byteArray = new byte[( int) file.length()];//可以在構造參數中傳入buffer大小InputStream is = new BufferedInputStream( new FileInputStream(file),2*1024);int size = is.read( byteArray);System. out.println( "大小:" + size + ";內容:" + new String(byteArray));is.close();
}
? ? ? ?關于如何設置buffer的大小,我們應根據我們的硬件狀況來確定。對于磁盤IO來說,如果硬盤每次讀取4KB大小的文件塊,那么我們最好設置成這個大小的整數倍。因為磁盤對于順序讀的效率是特別高的,所以如果buffer再設置的大寫可能會帶來更好的效率,比如設置成4*4KB或8*4KB。
? ? ? ?還需要注意一點的就是磁盤本身就會有緩存,在這種情況下,BufferedInputStream會一次讀取磁盤緩存大小的數據,而不是分多次的去讀。所以要想得到一個最優的buffer值,我們必須得知道磁盤每次讀的塊大小和其緩存大小,然后根據多次試驗的結果來得到最佳的buffer大小。
? ? ? ?BufferedOutputStream的情況和BufferedInputStream一致,在這里就不多做描述了。
9、Java IO:BufferedReader和BufferedWriter
? ? ? ?BufferedReader、BufferedWriter?的作用基本和BufferedInputStream、BufferedOutputStream一致,具體用法和原理都差不多 ,只不過一個是面向字符流一個是面向字節流。同樣,我們將改造字符流中的例4,給其加上buffer功能,看例子:
public static void readByBufferedReader() throws IOException {File file = new File( "d:/test.txt");// 在字符流基礎上用buffer流包裝,也可以指定buffer的大小Reader reader = new BufferedReader( new FileReader(file),2*1024);char[] byteArray = new char[( int) file.length()];int size = reader.read( byteArray);System. out.println( "大小:" + size + ";內容:" + new String(byteArray));reader.close();
}