檔案輸入輸出流與位元組陣列輸入輸出流的對接

2021-10-05 22:41:38 字數 2341 閱讀 3732

過程:

1)檔案–>【程式】–>位元組陣列

2)位元組陣列–>【程式】–>檔案

方式一:分開寫,比較簡單

思路:過程一:將檔案中的內容不斷通過程式【使用fileinputstream讀取檔案,使用bytearrayoutputstream寫入到緩衝陣列】讀到緩衝陣列中,

過程二:將緩衝陣列的內容不斷地通過程式【使用bytearrayinputstream讀取緩衝陣列中的內容,使用fileoutputstrem將寫入到檔案中】寫入到檔案中;

方式一完整**如下:

/**

* 分開寫對接

* 1)檔案--》位元組陣列

* 2)位元組陣列--》檔案

* @author dell

* */

public

class

fileandbyteconclusion02

baos.

flush()

;//4.釋放

fis.

close()

;return baos.

tobytearray()

;}public

static

void

bytearraytofile

(string destfilepath,

byte

buf)

throws ioexception

fos.

flush()

;//4.關閉

fos.

close()

; bais.

close()

;}public

static

void

main

(string[

] args)

throws ioexception

}

方式二:將上述過程1、2合併,【會有點繞,因為需要得到緩衝區中最新的內容,需不斷地覆蓋buf3】

思路:首先每次通過程式【使用fileinputstream】讀取檔案file1中的內容【理論大小為buf.length,實際為len可能小於理論大小】,將內容通過程式【使用byteoutputstream】寫入到緩衝容器中,同時將緩衝容器中的內容放置buf2位元組陣列中,完成過程一【見如下**】;

while

((len=fis.

read

(buf))!=

-1) fos.

write

(buf3,

0,len)

;//將buf3中的寫入到檔案file2中

完整**如下:

需要注意此處的buf和buf3的大小需一致。

因為buf3存放:緩衝區中最新的內容,

buf存放:讀取file1中的內容

,兩者相同,故大小需一致

fos.

write

(buf3,

0,len)

;//將buf3中的寫入到檔案file2中

方式二完整**如下

/**

* 將檔案輸入輸出流,位元組陣列輸入輸入流聯絡

*此處檔案輸入流讀取的是 緩衝區中最新的資料,而不是緩衝區中的資料,

* */

public

class

fileandbyteconclusion

// system.out.print(new string(buf3,0,len));

fos.

write

(buf3,

0,len)

;//將buf3中的寫入到檔案file2中

// system.out.print("就幾句");

// system.out.println();

// system.out.println("\r\nlen2:"+len2+" len:"+len);

} fos.

flush()

;}catch

(ioexception e)

finally

}catch

(exception e)

try}

catch

(exception e)

try}

catch

(exception e)

try}

catch

(exception e)}}

public

static

void

main

(string[

] args)

}

位元組陣列輸入流和位元組陣列輸出流實現檔案的拷貝

整理思路如下 為什麼要這樣進行copy 我更願意稱它為傳輸 因為這樣以二進位制的形式傳輸檔案,可以實現檔案的遠距離傳輸,即通過這樣可以實現伺服器與使用者之間檔案的傳輸。我們在本地傳送請求時,計算機將請求編碼為二進位制檔案,當傳送到伺服器後,伺服器將二進位制檔案進行解碼,從而實現檔案的傳輸 那麼如何將...

位元組輸入 輸出流

讀寫方法 void writeobject object obj 寫物件 object readobject 讀物件 注意 物件序列化 serializable 的問題 1 保證物件是序列化 實現serializable介面 的 2 不希望序列化的物件要用關鍵字transient修飾。reader類...

檔案輸入輸出流

學習內容 1.fileinputstream類 常用構造方法 fileinputstream string name 使用檔名建立fileinputstream物件 fileinputstream file file 使用file物件建立fileinputstream物件 2.fileonputst...