java - 输入流的迭代器

标签 java iterator inputstream

在练习中,我必须为 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/

相关文章:

java - Java 中的 Lambda 与迭代器

java - 从 RXTX 添加和获取通信端口

c++ - STL 容器中的内存释放

java - ObjectInputStream 对 FileInputStream 满意,对 getResourceAsStream 不满意

java - Socket.getInputStream().read(byte[]) 是否保证在至少读取一些数据后不会阻塞?

java - 接口(interface) ColorSpace 无法定义初始值设定项

Java - 使用 HashMap 与使用单独的类存储名称字段

java - 找不到类型的匹配 bean ... 依赖项

java - 关于执行 BufferedReader.readLine() : Unexpected end of ZILB input stream

java - 如何从 web start 下运行的客户端获取 Java 堆栈跟踪?