ユーティリティ・クラスの作成〜スケジュール管理ソフトをS!アプリで作ってみよう(その22)

HTTPでの応答(特にヘッダ部)を解析する時に、行単位で処理したい事が多い。そのため、InputStreamから文字を行単位で読み込むクラスを作成した。

Java SEの場合は、java.io.BufferedReaderというクラスがあり、それを使えばよいのだが、Java MEの場合は自分で作らないといけないようだ。(組込みはつらいよ...)

他にアプリを作ったときにも使えそうなので、別パッケージにしている。


package com.ettem.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class InputStreamReaderLine extends InputStreamReader {
private int readChar = -1;

public InputStreamReaderLine(InputStream is) {
super(is);
}

public InputStreamReaderLine(InputStream is, String enc)
throws UnsupportedEncodingException {
super(is, enc);
}

public String readLine() throws IOException {
try {
StringBuffer line = new StringBuffer();

if (readChar == -1 && (readChar = read()) == -1) {
return null;
}

do {
if (readChar == '\n') {
readChar = read();
break;
} else if (readChar == '\r') {
if ((readChar = read()) == '\n') {
readChar = read();
}
break;
} else {
line.append(readChar);
}
} while ((readChar = read()) == -1);

return line.toString();
} catch (IOException e) {
throw e;
}
}
}