In a exercise, I have to create an iterator for an InputStream. The goal is that the user can do :
for(byte b : new InputStreamToIterable(myInputStream)){ //do stuff with byte } I finished to create it and it works well, but the Iterator method is not very elegant (lot of 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(); } } Is there a way to make it nicer ?