在练习中,我必须为 InputStream 创建一个迭代器。目标是用户可以执行以下操作:
for(byte b : new InputStreamToIterable(myInputStream)){
//do stuff with byte
}
我完成了创建它并且它运行良好,但是迭代器method
不是很优雅(很多try/catch
)。
@Override
public Iterator<Byte> iterator() {
// TODO Auto-generated method stub
try {
return new Iterator<Byte>() {
int data = is.read();
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return data != -1;
}
@Override
public Byte next() {
// TODO Auto-generated method stub
if(!hasNext()){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int a = data;
try {
data = is.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (byte)a;
}
@Override
public void remove() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}
};
} catch (IOException e) {
// TODO Auto-generated catch block
throw new UnsupportedOperationException();
}
}
有没有办法让它变得更好?