Re: [問題] Java I/O 讀取不同 type 的 data stream
※ 引述《muzfan (muzfan)》之銘言:
: 大概像這樣:
: PrintStream ps = new PrintStream(theSocket.getOutputStream());
: ps.print(command + "\r\n");
: BufferedInputStream in = new BufferedInputStream(theSocket.getInputStream());
: BufferedReader r = new BufferedReader(new InputStreamReader(in));
: r.readLine();
: BufferedOutputStream out
: = new BufferedOutputStream(new FileOutputStream("image.png"));
: int i = 0;
: while ((i = in.read()) != -1) {
: out.write(i);
: }
: out.flush();
: in.close();
: out.close();
: 執行的結果,可以成功讀取正確的 caracter stream 資料,
: 但是,儲存下來的 image.png 卻是不正確的
: 卡住好久了,不知道我哪邊有盲點或是錯誤?
要考慮到 Buffered[Reader/InputStream] 會 pre-consume data 到內部 buffer
的行為。
#1BFkvXaF
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 218.173.128.251
推
04/30 22:08, , 1F
04/30 22:08, 1F
假設你把一個 InputStream 包裝成 BufferedInputStream。
InputStream srcIn = ...;
BufferedInputStream in = new BufferedInputStream(srcIn);
in.read();
read() method 會 return 一個 int value 即是從 stream 消耗(讀取)的 1 bytes
data 的值(如果沒有遇到 EOF)。
但是 in.read() 執行之後,實際上 srcIn 被消耗的數據量可能已經大於 1 bytes。
(in.read() 操作執行時,會盡量把 srcIn stream 裡當時的 available data 都
consume 掉並存進內部的 buffer 裡。
※ 編輯: sbrhsieh 來自: 218.173.128.251 (04/30 23:31)
※ 編輯: sbrhsieh 來自: 218.173.128.251 (04/30 23:33)
推
04/30 23:58, , 2F
04/30 23:58, 2F
→
04/30 23:59, , 3F
04/30 23:59, 3F
→
05/01 00:22, , 4F
05/01 00:22, 4F
推
05/01 02:27, , 5F
05/01 02:27, 5F
討論串 (同標題文章)