Re: [問題] 串流讀取問題
※ 引述《a613204 (胖胖)》之銘言:
: 傳送的片斷程式碼
: ---------------------------------------------------------
: public void sendMessage()
: {
: message="From "+name+": "+input.getText();
: try
: {
: out.writeChar('M');
: out.writeUTF(message);
: out.flush();
: show.append(message);
: show.setCaretPosition(show.getText().length());
: input.setText("");
: }
: catch(IOException e)
: {
: }
: }
: 寫的是網路資料傳送
: 寫法1 : message='M'+"From "+name+": "+input.getText();
: out.writeUTF(message);
: 寫法2 : message="From "+name+": "+input.getText();
: out.writeChar('M');
: out.writeUTF(message);
: 想請問這兩種寫法有差別嗎??
: 因為讀取時候用第二種寫法,readChar() 可以讀到第一個字是'M'
: 但是第一種寫法好像不行
: 請問這兩種寫法有差別嗎? 差在哪裡呢?
有差別。
看一下 java.io.DataOutput 的 API doc。
writeUTF 會先送出 2 bytes 的數據(表示接下來的 UTF byte sequence 長度),
再送出指定字串經 UTF-8 編碼 encode 之後的 byte sequence。
out.writeChar('M');
out.writeUTF('Hello');
=> 0x4D 0x00 0x05 0x48 0x65 0x6C 0x6C 0x6F
M H e l l o
================================================
out.writeUTF('MHello');
=> 0x00 0x06 0x4D 0x48 0x65 0x6C 0x6C 0x6F
M H e l l e
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 218.173.137.252
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):