001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.commons.collections.primitives.adapters.io;
018
019 import java.io.IOException;
020 import java.io.Reader;
021 import java.util.NoSuchElementException;
022
023 import org.apache.commons.collections.primitives.CharIterator;
024
025 /**
026 * Adapts a {@link Reader} to the {@link CharIterator} interface.
027 *
028 * @version $Revision: 480462 $ $Date: 2006-11-29 09:15:00 +0100 (Wed, 29 Nov 2006) $
029 * @author Rodney Waldhoff
030 */
031 public class ReaderCharIterator implements CharIterator {
032
033 public ReaderCharIterator(Reader in) {
034 this.reader = in;
035 }
036
037 public static CharIterator adapt(Reader in) {
038 return null == in ? null : new ReaderCharIterator(in);
039 }
040
041 public boolean hasNext() {
042 ensureNextAvailable();
043 return (-1 != next);
044 }
045
046 public char next() {
047 if(!hasNext()) {
048 throw new NoSuchElementException("No next element");
049 } else {
050 nextAvailable = false;
051 return (char)next;
052 }
053 }
054
055 /**
056 * Not supported.
057 * @throws UnsupportedOperationException
058 */
059 public void remove() throws UnsupportedOperationException {
060 throw new UnsupportedOperationException("remove() is not supported here");
061 }
062
063 private void ensureNextAvailable() {
064 if(!nextAvailable) {
065 readNext();
066 }
067 }
068
069 private void readNext() {
070 try {
071 next = reader.read();
072 nextAvailable = true;
073 } catch(IOException e) {
074 // TODO: Use a tunnelled exception instead?
075 // See http://radio.weblogs.com/0122027/2003/04/01.html#a7, for example
076 throw new RuntimeException(e.toString());
077 }
078 }
079
080 private Reader reader = null;
081 private boolean nextAvailable = false;
082 private int next;
083
084 }