Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2007 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.io;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.base.Preconditions.checkPositionIndexes;
 
 
 import java.io.Reader;
 import java.io.Writer;
 import java.util.List;

Provides utility methods for working with character streams.

All method parameters must be non-null unless documented otherwise.

Some of the methods in this class take arguments with a generic type of Readable & Closeable. A java.io.Reader implements both of those interfaces. Similarly for Appendable & Closeable and java.io.Writer.

Author(s):
Chris Nokleberg
Bin Zhu
Colin Decker
Since:
1.0
 
 public final class CharStreams {
   private static final int BUF_SIZE = 0x800; // 2K chars (4K bytes)
 
   private CharStreams() {}

  
Returns a factory that will supply instances of java.io.StringReader that read a string value.

Parameters:
value the string to read
Returns:
the factory
 
       final String value) {
     return asInputSupplier(CharSource.wrap(value));
   }

  
Returns a CharSource that reads the given string value.

Deprecated:
Use CharSource.wrap(java.lang.CharSequence) instead. This method is scheduled to be removed in Guava 16.0.
Since:
14.0
 
   public static CharSource asCharSource(String string) {
     return CharSource.wrap(string);
   }

  
Returns a factory that will supply instances of java.io.InputStreamReader, using the given java.io.InputStream factory and character set.

Parameters:
in the factory that will be used to open input streams
charset the charset used to decode the input stream; see com.google.common.base.Charsets for helpful predefined constants
Returns:
the factory
 
       final InputSupplier<? extends InputStreaminfinal Charset charset) {
     return asInputSupplier(
        ByteStreams.asByteSource(in).asCharSource(charset));
  }

  
Returns a factory that will supply instances of java.io.OutputStreamWriter, using the given java.io.OutputStream factory and character set.

Parameters:
out the factory that will be used to open output streams
charset the charset used to encode the output stream; see com.google.common.base.Charsets for helpful predefined constants
Returns:
the factory
      final OutputSupplier<? extends OutputStreamoutfinal Charset charset) {
    return asOutputSupplier(
        ByteStreams.asByteSink(out).asCharSink(charset));
  }

  
Writes a character sequence (such as a string) to an appendable object from the given supplier.

Parameters:
from the character sequence to write
to the output supplier
Throws:
java.io.IOException if an I/O error occurs
  public static <W extends Appendable & Closeablevoid write(CharSequence from,
      OutputSupplier<W> tothrows IOException {
    asCharSink(to).write(from);
  }

  
Opens java.lang.Readable and java.lang.Appendable objects from the given factories, copies all characters between the two, and closes them.

Parameters:
from the input factory
to the output factory
Returns:
the number of characters copied
Throws:
java.io.IOException if an I/O error occurs
  public static <R extends Readable & Closeable,
      W extends Appendable & Closeablelong copy(InputSupplier<R> from,
      OutputSupplier<W> tothrows IOException {
    return asCharSource(from).copyTo(asCharSink(to));
  }

  
Opens a java.lang.Readable object from the supplier, copies all characters to the java.lang.Appendable object, and closes the input. Does not close or flush the output.

Parameters:
from the input factory
to the object to write to
Returns:
the number of characters copied
Throws:
java.io.IOException if an I/O error occurs
  public static <R extends Readable & Closeablelong copy(
      InputSupplier<R> fromAppendable tothrows IOException {
    return asCharSource(from).copyTo(to);
  }

  
Copies all characters between the java.lang.Readable and java.lang.Appendable objects. Does not close or flush either object.

Parameters:
from the object to read from
to the object to write to
Returns:
the number of characters copied
Throws:
java.io.IOException if an I/O error occurs
  public static long copy(Readable fromAppendable tothrows IOException {
    checkNotNull(from);
    checkNotNull(to);
    CharBuffer buf = CharBuffer.allocate();
    long total = 0;
    while (from.read(buf) != -1) {
      buf.flip();
      to.append(buf);
      total += buf.remaining();
      buf.clear();
    }
    return total;
  }

  
Reads all characters from a java.lang.Readable object into a java.lang.String. Does not close the Readable.

Parameters:
r the object to read from
Returns:
a string containing all the characters
Throws:
java.io.IOException if an I/O error occurs
  public static String toString(Readable rthrows IOException {
    return toStringBuilder(r).toString();
  }

  
Returns the characters from a java.lang.Readable & java.io.Closeable object supplied by a factory as a java.lang.String.

Parameters:
supplier the factory to read from
Returns:
a string containing all the characters
Throws:
java.io.IOException if an I/O error occurs
  public static <R extends Readable & CloseableString toString(
      InputSupplier<R> supplierthrows IOException {
    return asCharSource(supplier).read();
  }

  
Reads all characters from a java.lang.Readable object into a new java.lang.StringBuilder instance. Does not close the Readable.

Parameters:
r the object to read from
Returns:
a java.lang.StringBuilder containing all the characters
Throws:
java.io.IOException if an I/O error occurs
  private static StringBuilder toStringBuilder(Readable rthrows IOException {
    StringBuilder sb = new StringBuilder();
    copy(rsb);
    return sb;
  }

  
Reads the first line from a java.lang.Readable & java.io.Closeable object supplied by a factory. The line does not include line-termination characters, but does include other leading and trailing whitespace.

Parameters:
supplier the factory to read from
Returns:
the first line, or null if the reader is empty
Throws:
java.io.IOException if an I/O error occurs
  public static <R extends Readable & CloseableString readFirstLine(
      InputSupplier<R> supplierthrows IOException {
    return asCharSource(supplier).readFirstLine();
  }

  
Reads all of the lines from a java.lang.Readable & java.io.Closeable object supplied by a factory. The lines do not include line-termination characters, but do include other leading and trailing whitespace.

Parameters:
supplier the factory to read from
Returns:
a mutable java.util.List containing all the lines
Throws:
java.io.IOException if an I/O error occurs
  public static <R extends Readable & CloseableList<StringreadLines(
      InputSupplier<R> supplierthrows IOException {
    Closer closer = Closer.create();
    try {
      R r = closer.register(supplier.getInput());
      return readLines(r);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

  
Reads all of the lines from a java.lang.Readable object. The lines do not include line-termination characters, but do include other leading and trailing whitespace.

Does not close the Readable. If reading files or resources you should use the Files.readLines(java.io.File,java.nio.charset.Charset) and Resources.readLines(java.net.URL,java.nio.charset.Charset) methods.

Parameters:
r the object to read from
Returns:
a mutable java.util.List containing all the lines
Throws:
java.io.IOException if an I/O error occurs
  public static List<StringreadLines(Readable rthrows IOException {
    List<Stringresult = new ArrayList<String>();
    LineReader lineReader = new LineReader(r);
    String line;
    while ((line = lineReader.readLine()) != null) {
      result.add(line);
    }
    return result;
  }

  
Streams lines from a java.lang.Readable object, stopping when the processor returns false or all lines have been read and returning the result produced by the processor. Does not close readable. Note that this method may not fully consume the contents of readable if the processor stops processing early.

Throws:
java.io.IOException if an I/O error occurs
Since:
14.0
  public static <T> T readLines(
      Readable readableLineProcessor<T> processorthrows 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();
  }

  
Streams lines from a java.lang.Readable and java.io.Closeable object supplied by a factory, stopping when our callback returns false, or we have read all of the lines.

Parameters:
supplier the factory to read from
callback the LineProcessor to use to handle the lines
Returns:
the output of processing the lines
Throws:
java.io.IOException if an I/O error occurs
  public static <R extends Readable & Closeable, T> T readLines(
      InputSupplier<R> supplierLineProcessor<T> callbackthrows IOException {
    checkNotNull(supplier);
    checkNotNull(callback);
    Closer closer = Closer.create();
    try {
      R r = closer.register(supplier.getInput());
      return readLines(rcallback);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

  
Joins multiple java.io.Reader suppliers into a single supplier. Reader returned from the supplier will contain the concatenated data from the readers of the underlying suppliers.

Reading from the joined reader will throw a java.lang.NullPointerException if any of the suppliers are null or return null.

Only one underlying reader will be open at a time. Closing the joined reader will close the open underlying reader.

Parameters:
suppliers the suppliers to concatenate
Returns:
a supplier that will return a reader containing the concatenated data
  public static InputSupplier<Readerjoin(
      final Iterable<? extends InputSupplier<? extends Reader>> suppliers) {
    checkNotNull(suppliers);
    Iterable<CharSourcesources = Iterables.transform(suppliers,
        new Function<InputSupplier<? extends Reader>, CharSource>() {
          @Override
          public CharSource apply(InputSupplier<? extends Readerinput) {
            return asCharSource(input);
          }
        });
    return asInputSupplier(CharSource.concat(sources));
  }

  
Varargs form of join(java.lang.Iterable).
  @SuppressWarnings("unchecked"// suppress "possible heap pollution" warning in JDK7
  public static InputSupplier<Readerjoin(
      InputSupplier<? extends Reader>... suppliers) {
    return join(Arrays.asList(suppliers));
  }

  
Discards n characters of data from the reader. This method will block until the full amount has been skipped. Does not close the reader.

Parameters:
reader the reader to read from
n the number of characters to skip
Throws:
java.io.EOFException if this stream reaches the end before skipping all the characters
java.io.IOException if an I/O error occurs
  public static void skipFully(Reader readerlong nthrows 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;
      }
    }
  }

  
Returns a java.io.Writer that simply discards written chars.

Since:
15.0
  public static Writer nullWriter() {
    return .;
  }
  private static final class NullWriter extends Writer {
    private static final NullWriter INSTANCE = new NullWriter();
    @Override
    public void write(int c) {
    }
    @Override
    public void write(char[] cbuf) {
      checkNotNull(cbuf);
    }
    @Override
    public void write(char[] cbufint offint len) {
      checkPositionIndexes(offoff + lencbuf.length);
    }
    @Override
    public void write(String str) {
      checkNotNull(str);
    }
    @Override
    public void write(String strint offint len) {
      checkPositionIndexes(offoff + lenstr.length());
    }
    @Override
    public Writer append(CharSequence csq) {
      checkNotNull(csq);
      return this;
    }
    @Override
    public Writer append(CharSequence csqint startint end) {
      checkPositionIndexes(startendcsq.length());
      return this;
    }
    @Override
    public Writer append(char c) {
      return this;
    }
    @Override
    public void flush() {
    }
    @Override
    public void close() {
    }
    @Override
    public String toString() {
      return "CharStreams.nullWriter()";
    }
  }

  
Returns a Writer that sends all output to the given java.lang.Appendable target. Closing the writer will close the target if it is java.io.Closeable, and flushing the writer will flush the target if it is java.io.Flushable.

Parameters:
target the object to which output will be sent
Returns:
a new Writer object, unless target is a Writer, in which case the target is returned
  public static Writer asWriter(Appendable target) {
    if (target instanceof Writer) {
      return (Writertarget;
    }
    return new AppendableWriter(target);
  }
  // TODO(user): Remove these once Input/OutputSupplier methods are removed
  static Reader asReader(final Readable readable) {
    checkNotNull(readable);
    if (readable instanceof Reader) {
      return (Readerreadable;
    }
    return new Reader() {
      @Override
      public int read(char[] cbufint offint lenthrows IOException {
        return read(CharBuffer.wrap(cbufofflen));
      }
      @Override
      public int read(CharBuffer targetthrows IOException {
        return readable.read(target);
      }
      @Override
      public void close() throws IOException {
        if (readable instanceof Closeable) {
          ((Closeablereadable).close();
        }
      }
    };
  }

  
Returns a view of the given Readable supplier as a CharSource.

This method is a temporary method provided for easing migration from suppliers to sources and sinks.

Since:
15.0
  public static CharSource asCharSource(
      final InputSupplier<? extends Readablesupplier) {
    checkNotNull(supplier);
    return new CharSource() {
      @Override
      public Reader openStream() throws IOException {
        return asReader(supplier.getInput());
      }
      @Override
      public String toString() {
        return "CharStreams.asCharSource(" + supplier + ")";
      }
    };
  }

  
Returns a view of the given Appendable supplier as a CharSink.

This method is a temporary method provided for easing migration from suppliers to sources and sinks.

Since:
15.0
  public static CharSink asCharSink(
      final OutputSupplier<? extends Appendablesupplier) {
    checkNotNull(supplier);
    return new CharSink() {
      @Override
      public Writer openStream() throws IOException {
        return asWriter(supplier.getOutput());
      }
      @Override
      public String toString() {
        return "CharStreams.asCharSink(" + supplier + ")";
      }
    };
  }
  @SuppressWarnings("unchecked"// used internally where known to be safe
  static <R extends ReaderInputSupplier<R> asInputSupplier(
      CharSource source) {
    return (InputSuppliercheckNotNull(source);
  }
  @SuppressWarnings("unchecked"// used internally where known to be safe
  static <W extends WriterOutputSupplier<W> asOutputSupplier(
      CharSink sink) {
    return (OutputSuppliercheckNotNull(sink);
  }
New to GrepCode? Check out our FAQ X