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
(Readable from, Appendable to)
| 63 | * @throws IOException if an I/O error occurs |
| 64 | */ |
| 65 | @CanIgnoreReturnValue |
| 66 | public static long copy(Readable from, Appendable to) throws IOException { |
| 67 | // The most common case is that from is a Reader (like InputStreamReader or StringReader) so |
| 68 | // take advantage of that. |
| 69 | if (from instanceof Reader) { |
| 70 | // optimize for common output types which are optimized to deal with char[] |
| 71 | if (to instanceof StringBuilder) { |
| 72 | return copyReaderToBuilder((Reader) from, (StringBuilder) to); |
| 73 | } else { |
| 74 | return copyReaderToWriter((Reader) from, asWriter(to)); |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | checkNotNull(from); |
| 79 | checkNotNull(to); |
| 80 | long total = 0; |
| 81 | CharBuffer buf = createBuffer(); |
| 82 | while (from.read(buf) != -1) { |
| 83 | Java8Compatibility.flip(buf); |
| 84 | to.append(buf); |
| 85 | total += buf.remaining(); |
| 86 | Java8Compatibility.clear(buf); |
| 87 | } |
| 88 | return total; |
| 89 | } |
| 90 | |
| 91 | // TODO(lukes): consider allowing callers to pass in a buffer to use, some callers would be able |
| 92 | // to reuse buffers, others would be able to size them more appropriately than the constant |