Java IO一般大家常說的IO分為兩個部分: 1.java.io包中堵塞型IO(BIO);2.java.nio包中的非堵塞型IO,通常稱為New IO(NIO)。當(dāng)然還有一個AIO,即異步IO。本篇說的是BIO。
在整個Java.io包中最重要的就是5個類和一個接口。5個類指的是File、OutputStream、InputStream、Writer、Reader;一個接口指的是Serializable.掌握了這些IO的核心操作那么對于Java中的IO體系也就有了一個初步的認識了
Java I/O主要包括如下幾個層次,包含三個部分:
1.流式部分――IO的主體部分;
2.非流式部分――主要包含一些輔助流式部分的類,如:File類、RandomAccessFile類等;
3.其他類--文件讀取部分的與安全相關(guān)的類,如:SerializablePermission類,以及與本地操作系統(tǒng)相關(guān)的文件系統(tǒng)的類,如:FileSystem類和Win32FileSystem類和WinNTFileSystem類。
? 主要的類如下:
? ? 1. File(文件特征與管理):用于文件或者目錄的描述信息,例如生成新目錄,修改文件名,刪除文件,判斷文件所在路徑等。
? ? 2. InputStream(二進制格式操作):抽象類,基于字節(jié)的輸入操作,是所有輸入流的父類。定義了所有輸入流都具有的共同特征。
? ? 3. OutputStream(二進制格式操作):抽象類?;谧止?jié)的輸出操作。是所有輸出流的父類。定義了所有輸出流都具有的共同特征。
InputStream和OutputStream類圖如下:

當(dāng)然還有一些很有用的類,如:ZipInputStream,ZipOutputStream,這些都是常用的ZIP壓縮格式讀寫文件;
public class TestZipInputStream{
? ? public static void main ( String [ ] args ) throws ZipException ,IOException{
? ? ? ? File file = new File ( "/home/piziyu/ziptest/test.zip" ) ;
? ? ? ? ZipFile zipFile = new ZipFile ( file ) ;
? ? ? ? // 創(chuàng)建 ZipInputStream 實例
? ? ? ? ZipInputStream zis = new ZipInputStream ( new FileInputStream ( file ) ) ;
? ? ? ? ZipEntry entry = null ;
? ? ? ? while ( ( entry = zis.getNextEntry ( ) ) != null )? {
? ? ? ? ? ? System.out.println ( "decompress file :" + entry.getName ( ) ) ;
? ? ? ? ? ? File outFile = new File ( "/home/liangruihua/ziptest/" + entry.getName ( ) ) ;
? ? ? ? ? ? // 創(chuàng)建目錄
? ? ? ? ? ? if ( ! outFile.getParentFile ( ).exists ( ) )? {
? ? ? ? ? ? ? ? outFile.getParentFile ( ).mkdir ( ) ;
? ? ? ? ? ? }
? ? ? ? ? ? // 如果沒有就創(chuàng)建一個
? ? ? ? ? ? if ( ! outFile.exists ( ) ) {
? ? ? ? ? ? ? ? outFile.createNewFile ( ) ;
? ? ? ? ? ? }
? ? ? ? ? ? BufferedInputStream bis = new BufferedInputStream (zipFile.getInputStream ( entry ) ) ;
? ? ? ? ? ? // 創(chuàng)建 outputstream
? ? ? ? ? ? BufferedOutputStream bos = new BufferedOutputStream (new FileOutputStream ( outFile ) ) ;
? ? ? ? ? ? byte [ ] b = new byte [ 100 ] ;
? ? ? ? ? ? while ( true )
? ? ? ? ? ? {
? ? ? ? ? ? ? ? int len = bis.read ( b ) ;
? ? ? ? ? ? ? ? if ( len == - 1 )
? ? ? ? ? ? ? ? ? ? break ;
? ? ? ? ? ? ? ? bos.write ( b , 0 , len ) ;
? ? ? ? ? ? }
? ? ? ? ? ? bis.close ( ) ;//更應(yīng)該在finally中關(guān)閉
? ? ? ? ? ? bos.close ( ) ;
? ? ? ? }
? ? ? ? zis.close ( ) ;
? ? }
}