View
227
Download
2
Embed Size (px)
Citation preview
Lab2 Brief Introduction• 學習重點– 如何實作 FilterInputStream, FilterOutputStream– 使用 Java IO (ex: 存取檔案 )
• 工作項目– 實作 EndianTranslationInputStream class– 實作 EndianTranslationOutputStream class– 實作 writeTo(InputStream in, OutputStream out)– 實作 readFile(String fileName)– 上述 Class 與 method 的使用範例
Endian?• 16-bit(2-byte) 的數字儲存在記憶體中的方式– ex: 4398110 = ABCD16
Memory Address
Data0 1
CD AB
Memory Address
Data0 1
AB CD
Little-endian
Big-endian
ByteArrayInputStream
For Example …
AB CD 1A 2B 3C 4D0 1 2 3 4 5
InputStream in =
in.read() returns ABin.read() returns CDin.read() returns 1A…
EndianTranslationInputStream
Endian Translate Filter…
ByteArrayInputStream
AB CD 1A 2B 3C 4D0 1 2 3 4 5
InputStream in =
in.read() returns ABin.read() returns CD
in.read() returns …
2B
Methods• int read()
EndianTranslationInputStreamInputStream in =
int read() in.read() x 2 => Buffer;Buffer( )return Buffer[1];
ByteArrayInputStream
AB CD
1A 2B 3C 4D0 1 2 3 4 5
AB CD
• int read(byte[] b, int off, int len)– 一次讀 len 個 byte ,並且放到 b[off] … b[len-1]– 回傳總共讀了幾個 byte
EndianTranslationInputStreamInputStream in =
int read(byte[] b, int off, int len) this.read() x len…
ByteArrayInputStream
1A 2B 3C 4D0 1 2 3 4 5
AB CD
Trace Source Code
• java.io.FilterInputStream• java.io.FilterOutputStream• java.io.BufferedInputStream
writeTo Method
• void writeTo(InputStream i, OutputStream o)– 將 InputStream 裡的東西,丟到 OutputStream– 簡單來說… o.write(i.read());
writeTo
檔案ByteArraySocket ( 網路 )…
檔案ByteArraySocket ( 網路 )…
readFile Method
• void readFile(String fileName)– InputStream in =
– System.out.print(Interger.toHexString(in.read() ));– until in.read() == -1
EndianTranslationInputStreamFileInputStream------------------------
“input.txt”
UTF-16BE UTF-16LE• UTF-16BE– 一個字用 16-bit 來表示,以 Big-endian 方式儲
存• UTF-16LE– 一個字用 16-bit 來表示,以 Big-endian 方式儲
存
UTF-16BE UTF-16LE• “ARX”.getBytes(“UTF-16BE”)
• “ARX”.getBytes(“UTF-16LE”)
00 52 00 580 1 2 3 4 5
00 41
A R X
0052 00580 1 2 3 4 5
0041
A R X
Main method example1. 由一個字串建立 Byte Array (UTF-16BE)
2. 將這個 ByteArray 轉換 Endian 後存入” out.txt”– 利用 writeTo()
3. 直接讀取” out.txt”
00 52 00 580 1 2 3 4 5
00 41
0052 00580 1 2 3 4 5
0041
Main method example4. 利用 readFile() 讀取” out.txt”
5. 用文字編輯器打開” out.txt”– 選擇編碼: UTF-16LE
00 52 00 580 1 2 3 4 5
00 41
EndianTranslationInputStream
BufferedInputStream
Try this …
EndianTranslationInputStreamByteArrayInputStream
BufferedInputStreamEndianTranslationInputStream
ByteArrayInputStream
Q1: 有規定檔案輸入輸出的編碼嗎?A: No, 只要能展示出你寫的 Filter, writeTo, readFile正確運作即可
Q2: 萬一 InputStream 是單數個 Byte ?A: 你可以多補一個 byte(0) ,或是丟 Exception
Q3: Demo 時會故意用 read(byte[] b, ….) ?A: 我應該不會直接去用,但是我會掛一個BufferedInputStream 在外面,這樣就會用到該method