Re: [問題] Java I/O 讀取不同 type 的 data stream
※ 引述《sbrhsieh (偶爾想擺爛一下)》之銘言:
: ※ 引述《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
感謝提醒。
我更改了我的程式如下:
public void saveImage(String command) {
try {
PrintStream ps = new PrintStream(theSocket.getOutputStream());
ps.print(command + "\r\n");
BufferedInputStream in = new
BufferedInputStream(theSocket.getInputStream());
clearEOL(in);
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();
} catch (IOException e) {
System.err.println("Err at saveImage(): " + e);
}
}
private void clearEOL(BufferedInputStream in) {
byte[] b = new byte[1];
boolean eol = false;
try {
while (in.read(b, 0, 1) != -1) {
// only stop when we see \r (13) followed by \n (10)
if(b[0] == 13) {
eol = true;
continue;
}
if(eol) {
if(b[0] == 10)
break;
eol = false;
}
}
} catch(IOException e) {
System.err.println("Err at clearEOL(): " + e);
}
}
先利用 clearEOL 過濾掉第一行的圖片字串資訊,然後再繼續讀取圖片的 binary data,
然而,所存下的圖片仍然是錯誤的,不知道我的程式碼哪邊有誤?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 130.95.99.105
※ 編輯: muzfan 來自: 130.95.99.105 (05/02 13:50)
→
05/02 16:47, , 1F
05/02 16:47, 1F
推
05/02 17:11, , 2F
05/02 17:11, 2F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 3 篇):