在练习中,我必须为 InputStream 创建一个迭代器。 目标是用户可以执行以下操作:
for(byte b : new InputStreamToIterable(myInputStream)){
//do stuff with byte
}
我完成了它的创建,并且运行良好,但是迭代器方法
不是很优雅(很多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();
}
}
有没有办法让它变得更好?
最佳答案
您可以通过在 next()
中组合两个 try-catch
block 来稍微清理它:
boolean isClosed = false;
@Override
public Byte next() {
if(isClosed) throw new NoSuchElementException();
int a = data;
try {
if(!hasNext()) {
is.close();
isClosed = true;
} else
data = is.read();
} catch(IOException e) { throw new RuntimeException(e); }
return (byte)a;
}
编辑
根据下面的讨论更改了代码
关于java - 输入流的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16319881/