天天看點

IO 輸入輸出 流 基本概念整理(FileInputStream,FileOutputStream)

IO 輸入輸出 流(FileInputStream,FileOutputStream)

資料的通信管道

1、沿着一定的方向

2、沿着一定的路徑

IO流

1、方向

輸入流(讀)input   特點: 有檔案則讀,無檔案則報異常!

從外部(檔案系統)  流入到  程式中 (jvm)

輸出流(寫)output  特點: 有檔案則覆寫,無檔案則建立檔案!(PS:可以追加,fos的第二個參數寫成true即可追加寫入)

從程式中  流入到  外部(檔案系統)

2、類型

位元組流byte  stream

處理二進制資料

字元流char reader/writer

處理字元資料

FileInputStream

3、功能

節點流

檔案的簡單的讀寫操作

包裝流

有一些其他方法。這些方法能夠使得程式員更加友善的

操作資料

橋梁流

基本上所有的流都遵循這樣的規則:

1、将流的名字分為三部分

partA  功能/特點

partB  方向

partC  類型

對象的字元輸出流

ObjectWriter

ObjectOutputStream

2、流 一般都是成對出現的

FileInputStream  FileOutputStream

FileReader  FileWriter

BufferedInputStreamReader

BufferedOutputStreamWriter

StringReader  StringWriter

System.in System.out

流:

占用資源

釋放資源:  關閉

模闆

FileInputStream fis = null;

try{

fis = new FileInputStream(f);

fis.read();

}

catch(Exception e)

{

}

finally{

fis.close();

}

public void someMethod()

{

FileInputStream fis = new FileInputStream(f);

fis.read();

......

fis.close();

}

public void otherMehtod()

{

try{

someMethod();

}catch(Exception e)

{

//asdasd

}

//do other things......

}

對于位元組輸入流:

avaliable

int i = read()

i 讀取到的資料

int i = read(byte[] b)

b 讀取到的資料

i 讀取的長度

判斷是否讀到檔案末尾?

i == -1

對于位元組輸出流

write(byte i)

write(byte[] b)

write(byte[] b ,int startIndex,int offset)

檔案讀取基本範例代碼,這裡是一個位元組一個位元組的讀取!:

    public static void main(String[] args)

    {

        FileInputStream fis = null;

        try

        {

            //要處理FileNotFoundException

            // 相對路徑 : 相對的是: 執行java指令所在的路徑

            //  eclipse 執行java指令  預設是在:coreJava

            fis = new FileInputStream(new File("src/com/itany/coreJava/day17/a.txt"));

            //要處理  IOException

            int b = 0;

            while((b = fis.read()) != -1)

            {

               // System.out.println(b);

            }

            System.out.println("end");

        }

        catch (Exception e)

        {

            e.printStackTrace();

        }finally{

            if(fis != null)

            {

                try

                {

                    fis.close();

                }

                catch (IOException e)

                {

                    e.printStackTrace();

                }

            }

        }

    }