示例#1
1
 /**
  * Discards {@code n} characters of data from the reader. This method will block until the full
  * amount has been skipped. Does not close the reader.
  *
  * @param reader the reader to read from
  * @param n the number of characters to skip
  * @throws EOFException if this stream reaches the end before skipping all the characters
  * @throws IOException if an I/O error occurs
  */
 public static void skipFully(Reader reader, long n) throws IOException {
   checkNotNull(reader);
   while (n > 0) {
     long amt = reader.skip(n);
     if (amt == 0) {
       // force a blocking read
       if (reader.read() == -1) {
         throw new EOFException();
       }
       n--;
     } else {
       n -= amt;
     }
   }
 }
 @Override
 public SortedMap<R, Map<C, V>> subMap(R fromKey, R toKey) {
   checkNotNull(fromKey);
   checkNotNull(toKey);
   return new StandardRowSortedTable<R, C, V>(sortedBackingMap().subMap(fromKey, toKey), factory)
       .rowMap();
 }
示例#3
0
  /**
   * Streams lines from a {@link Readable} object, stopping when the processor returns {@code false}
   * or all lines have been read and returning the result produced by the processor. Does not close
   * {@code readable}. Note that this method may not fully consume the contents of {@code readable}
   * if the processor stops processing early.
   *
   * @throws IOException if an I/O error occurs
   * @since 14.0
   */
  public static <T> T readLines(Readable readable, LineProcessor<T> processor) throws IOException {
    checkNotNull(readable);
    checkNotNull(processor);

    LineReader lineReader = new LineReader(readable);
    String line;
    while ((line = lineReader.readLine()) != null) {
      if (!processor.processLine(line)) {
        break;
      }
    }
    return processor.getResult();
  }
示例#4
0
 /**
  * Copies all characters between the {@link Readable} and {@link Appendable} objects. Does not
  * close or flush either object.
  *
  * @param from the object to read from
  * @param to the object to write to
  * @return the number of characters copied
  * @throws IOException if an I/O error occurs
  */
 public static long copy(Readable from, Appendable to) throws IOException {
   checkNotNull(from);
   checkNotNull(to);
   CharBuffer buf = CharBuffer.allocate(BUF_SIZE);
   long total = 0;
   while (from.read(buf) != -1) {
     buf.flip();
     to.append(buf);
     total += buf.remaining();
     buf.clear();
   }
   return total;
 }
示例#5
0
  /**
   * Streams lines from a {@link Readable} and {@link Closeable} object supplied by a factory,
   * stopping when our callback returns false, or we have read all of the lines.
   *
   * @param supplier the factory to read from
   * @param callback the LineProcessor to use to handle the lines
   * @return the output of processing the lines
   * @throws IOException if an I/O error occurs
   * @deprecated Use {@link CharSource#readLines(LineProcessor)} instead. This method is scheduled
   *     for removal in Guava 18.0.
   */
  @Deprecated
  public static <R extends Readable & Closeable, T> T readLines(
      InputSupplier<R> supplier, LineProcessor<T> callback) throws IOException {
    checkNotNull(supplier);
    checkNotNull(callback);

    Closer closer = Closer.create();
    try {
      R r = closer.register(supplier.getInput());
      return readLines(r, callback);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }
示例#6
0
 /**
  * Drains the queue as {@link BlockingQueue#drainTo(Collection, int)}, but if the requested {@code
  * numElements} elements are not available, it will wait for them up to the specified timeout.
  *
  * @param q the blocking queue to be drained
  * @param buffer where to add the transferred elements
  * @param numElements the number of elements to be waited for
  * @param timeout how long to wait before giving up, in units of {@code unit}
  * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter
  * @return the number of elements transferred
  * @throws InterruptedException if interrupted while waiting
  */
 @Beta
 public static <E> int drain(
     BlockingQueue<E> q,
     Collection<? super E> buffer,
     int numElements,
     long timeout,
     TimeUnit unit)
     throws InterruptedException {
   Preconditions.checkNotNull(buffer);
   /*
    * This code performs one System.nanoTime() more than necessary, and in return, the time to
    * execute Queue#drainTo is not added *on top* of waiting for the timeout (which could make
    * the timeout arbitrarily inaccurate, given a queue that is slow to drain).
    */
   long deadline = System.nanoTime() + unit.toNanos(timeout);
   int added = 0;
   while (added < numElements) {
     // we could rely solely on #poll, but #drainTo might be more efficient when there are multiple
     // elements already available (e.g. LinkedBlockingQueue#drainTo locks only once)
     added += q.drainTo(buffer, numElements - added);
     if (added < numElements) { // not enough elements immediately available; will have to poll
       E e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS);
       if (e == null) {
         break; // we already waited enough, and there are no more elements in sight
       }
       buffer.add(e);
       added++;
     }
   }
   return added;
 }
示例#7
0
  /**
   * Returns an iterable that applies {@code convert} to each element of {@code fromIterable}. The
   * conversion is done lazily.
   *
   * <p>The returned iterable's iterator supports {@code remove()} if the input iterator does. After
   * a successful {@code remove()} call, {@code fromIterable} no longer contains the corresponding
   * element.
   */
  public Iterable<B> convertAll(final Iterable<? extends A> fromIterable) {
    checkNotNull(fromIterable, "fromIterable");
    return new Iterable<B>() {
      @Override
      public Iterator<B> iterator() {
        return new Iterator<B>() {
          private final Iterator<? extends A> fromIterator = fromIterable.iterator();

          @Override
          public boolean hasNext() {
            return fromIterator.hasNext();
          }

          @Override
          public B next() {
            return convert(fromIterator.next());
          }

          @Override
          public void remove() {
            fromIterator.remove();
          }
        };
      }
    };
  }
示例#8
0
  /**
   * Returns a view of the given {@code Appendable} supplier as a {@code CharSink}.
   *
   * <p>This method is a temporary method provided for easing migration from suppliers to sources
   * and sinks.
   *
   * @since 15.0
   * @deprecated Convert all {@code OutputSupplier<? extends Appendable>} implementations to extend
   *     {@link CharSink} or provide a method for viewing the object as a {@code CharSink}. This
   *     method is scheduled for removal in Guava 18.0.
   */
  @Deprecated
  public static CharSink asCharSink(final OutputSupplier<? extends Appendable> supplier) {
    checkNotNull(supplier);
    return new CharSink() {
      @Override
      public Writer openStream() throws IOException {
        return asWriter(supplier.getOutput());
      }

      @Override
      public String toString() {
        return "CharStreams.asCharSink(" + supplier + ")";
      }
    };
  }
示例#9
0
  /**
   * Returns a view of the given {@code Readable} supplier as a {@code CharSource}.
   *
   * <p>This method is a temporary method provided for easing migration from suppliers to sources
   * and sinks.
   *
   * @since 15.0
   * @deprecated Convert all {@code InputSupplier<? extends Readable>} implementations to extend
   *     {@link CharSource} or provide a method for viewing the object as a {@code CharSource}. This
   *     method is scheduled for removal in Guava 18.0.
   */
  @Deprecated
  public static CharSource asCharSource(final InputSupplier<? extends Readable> supplier) {
    checkNotNull(supplier);
    return new CharSource() {
      @Override
      public Reader openStream() throws IOException {
        return asReader(supplier.getInput());
      }

      @Override
      public String toString() {
        return "CharStreams.asCharSource(" + supplier + ")";
      }
    };
  }
示例#10
0
 /**
  * Joins multiple {@link Reader} suppliers into a single supplier. Reader returned from the
  * supplier will contain the concatenated data from the readers of the underlying suppliers.
  *
  * <p>Reading from the joined reader will throw a {@link NullPointerException} if any of the
  * suppliers are null or return null.
  *
  * <p>Only one underlying reader will be open at a time. Closing the joined reader will close the
  * open underlying reader.
  *
  * @param suppliers the suppliers to concatenate
  * @return a supplier that will return a reader containing the concatenated data
  * @deprecated Use {@link CharSource#concat(Iterable)} instead. This method is scheduled for
  *     removal in Guava 18.0.
  */
 @Deprecated
 public static InputSupplier<Reader> join(
     final Iterable<? extends InputSupplier<? extends Reader>> suppliers) {
   checkNotNull(suppliers);
   Iterable<CharSource> sources =
       Iterables.transform(
           suppliers,
           new Function<InputSupplier<? extends Reader>, CharSource>() {
             @Override
             public CharSource apply(InputSupplier<? extends Reader> input) {
               return asCharSource(input);
             }
           });
   return asInputSupplier(CharSource.concat(sources));
 }
示例#11
0
 /**
  * Drains the queue as {@linkplain #drain(BlockingQueue, Collection, int, long, TimeUnit)}, but
  * with a different behavior in case it is interrupted while waiting. In that case, the operation
  * will continue as usual, and in the end the thread's interruption status will be set (no {@code
  * InterruptedException} is thrown).
  *
  * @param q the blocking queue to be drained
  * @param buffer where to add the transferred elements
  * @param numElements the number of elements to be waited for
  * @param timeout how long to wait before giving up, in units of {@code unit}
  * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter
  * @return the number of elements transferred
  */
 @Beta
 public static <E> int drainUninterruptibly(
     BlockingQueue<E> q,
     Collection<? super E> buffer,
     int numElements,
     long timeout,
     TimeUnit unit) {
   Preconditions.checkNotNull(buffer);
   long deadline = System.nanoTime() + unit.toNanos(timeout);
   int added = 0;
   boolean interrupted = false;
   try {
     while (added < numElements) {
       // we could rely solely on #poll, but #drainTo might be more efficient when there are
       // multiple elements already available (e.g. LinkedBlockingQueue#drainTo locks only once)
       added += q.drainTo(buffer, numElements - added);
       if (added < numElements) { // not enough elements immediately available; will have to poll
         E e; // written exactly once, by a successful (uninterrupted) invocation of #poll
         while (true) {
           try {
             e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS);
             break;
           } catch (InterruptedException ex) {
             interrupted = true; // note interruption and retry
           }
         }
         if (e == null) {
           break; // we already waited enough, and there are no more elements in sight
         }
         buffer.add(e);
         added++;
       }
     }
   } finally {
     if (interrupted) {
       Thread.currentThread().interrupt();
     }
   }
   return added;
 }
示例#12
0
  static Reader asReader(final Readable readable) {
    checkNotNull(readable);
    if (readable instanceof Reader) {
      return (Reader) readable;
    }
    return new Reader() {
      @Override
      public int read(char[] cbuf, int off, int len) throws IOException {
        return read(CharBuffer.wrap(cbuf, off, len));
      }

      @Override
      public int read(CharBuffer target) throws IOException {
        return readable.read(target);
      }

      @Override
      public void close() throws IOException {
        if (readable instanceof Closeable) {
          ((Closeable) readable).close();
        }
      }
    };
  }
 @Override
 public SortedMap<R, Map<C, V>> headMap(R toKey) {
   checkNotNull(toKey);
   return new StandardRowSortedTable<R, C, V>(sortedBackingMap().headMap(toKey), factory)
       .rowMap();
 }
示例#14
0
 @Override
 public Writer append(CharSequence csq) {
   checkNotNull(csq);
   return this;
 }
示例#15
0
 @Override
 public void write(String str) {
   checkNotNull(str);
 }
示例#16
0
 @Override
 public void write(char[] cbuf) {
   checkNotNull(cbuf);
 }