IO流 位元組流讀寫 使用位元組輸入流讀資料

2021-10-14 15:48:01 字數 2757 閱讀 8470

public

class

fileoutputstreandemo

使用位元組輸出流完成位元組陣列的輸出

public

static

void

main

(string[

] args)

throws ioexception

;// 如果要寫出乙個字串 hello world

string str =

"hello world"

;byte

bytes1 = str.

getbytes()

;// 獲取字串相對應的位元組陣列

//寫位元組陣列的一部分

fos.

write

(bytes1,0,

5); fos.

close()

;}

public

static

void

main

(string[

] args)

throws ioexception

; fos.

write

(bytes)

;// 如果要寫出乙個字串 hello world

string str =

"hello world"

;byte

bytes1 = str.

getbytes()

;// 獲取字串相對應的位元組陣列

fos.

write

(bytes1)

;//寫位元組陣列的一部分

fos.

close()

;}

實現換行寫的功能:

換行功能: windows \r\n

linux \n

mac: \r

public

static

void

main

(string[

] args)

throws ioexception

; fos.

write

(bytes)

; fos.

write

("\r\n"

.getbytes()

);// 如果要寫出乙個字串 hello world

string str =

"hello world"

;byte

bytes1 = str.

getbytes()

;// 獲取字串相對應的位元組陣列

fos.

write

(bytes1)

; fos.

write

("\r\n"

.getbytes()

);// 寫出換行符

//寫位元組陣列的一部分

fos.

close()

;}}

io中異常的處理方式

public

static

void

main

(string[

] args)

catch

(filenotfoundexception e)

catch

(ioexception e)

finally

catch

(ioexception e)}}

}

使用位元組輸入流讀資料

fileinputstream 從檔案系統中的檔案獲取輸入位元組

fileinputstream(file file)

通過開啟與實際檔案的連線建立乙個 fileinputstream ,該檔案由檔案系統中的 file物件 file命名。

fileinputstream(string name)

通過開啟與實際檔案的連線來建立乙個 fileinputstream ,該檔案由檔案系統中的路徑名 name命名。

讀的方法

int read()

從該輸入流讀取乙個位元組的資料。

int read(byte b)

從該輸入流讀取最多 b.length個位元組的資料為位元組陣列。

int read(byte b, int off, int len)

從該輸入流讀取最多 len位元組的資料為位元組陣列。

void close()

關閉此檔案輸入流並釋放與流相關聯的任何系統資源。

public

static

void

main

(string[

] args)

throws ioexception

// 釋放資源

fis.

close()

;}

注意:使用位元組輸出流寫資料時,如果檔案不存在 ,系統會自動為我們建立乙個新檔案

使用位元組輸入流讀資料時,如果檔案不存在 則會報filenotfoundexception

讀取的過程

1 建立檔案表示要讀取的 檔案的路徑

2 建立fileinputstream 物件

3 讓fileinputstream物件指向檔案,如果檔案存在 則可以使用相應的方法去 讀取 ,如果不存在 則會爆出filenotfoundexception

IO流 位元組流

位元組輸出流outputstream 此抽象類,是表示輸出位元組流的所有類的超類。操作的資料都是位元組,定義了輸出位元組流的基本共性功能方法。輸出流中定義的方法 close 關閉輸出流並釋放與此輸出流有關的所有系統資源 flush 重新整理此輸出流並強制寫出所有緩衝的輸出位元組 write byte...

IO流位元組流

io流就是裝置之間的資料傳輸 位元組流 任意型別的檔案都能讀寫 位元組流的 抽象 基類 inputstream 輸入流 outoutstream 輸出流 fileoutputstream的三個write 方法 public void write int b 寫乙個位元組 超過乙個位元組 砍掉前面的位...

IO流 位元組流

io流分類 按資料的流向 輸入流 讀資料 輸出流 寫資料 按資料型別 位元組流 字元流 一般來說,我們說io流的分類是按照資料型別來分的。那麼這兩種流都在什麼情況下使用呢?如果資料通過windows子代的記事本軟體開啟,我們還可以讀懂裡面的內容,就是用字元流,否則使用位元組流。如果你不知道該使用哪種...