Library enhancement proposal for copying data from/to Reader/Writer InputStream/OutputStream

Patrick Reinhart patrick at reini.net
Thu Nov 27 13:01:31 UTC 2014


Added null checks also to Readable/Appendable copy methods

Patrick

> Am 27.11.2014 um 13:26 schrieb Pavel Rappo <pavel.rappo at oracle.com>:
> 
> At the bare minimum I would use runtime null/range checks and give a little bit more freedom for those who want to control buffer (or probably reuse already existing one): http://cr.openjdk.java.net/~prappo/ioutil/webrev.01/
> 
> I would also add some clarifications in the javadoc.
> 
> -Pavel
> 


diff -r 194458fe7339 src/java.base/share/classes/java/io/IOUtil.java
--- a/src/java.base/share/classes/java/io/IOUtil.java	Thu Nov 27 13:50:36 2014 +0100
+++ b/src/java.base/share/classes/java/io/IOUtil.java	Thu Nov 27 14:00:07 2014 +0100
@@ -71,7 +71,6 @@
      */
     public static long copy(InputStream source, OutputStream target,
                             byte[] buffer) throws IOException {
-
         Objects.requireNonNull(source, "source");
         Objects.requireNonNull(target, "target");
         Objects.requireNonNull(buffer, "buffer");
@@ -100,15 +99,15 @@
      * @throws IOException if an I/O error occurs when reading or writing
      */
     public static long copy(Readable source, Appendable target) throws IOException {
-        long totalRead = 0L;
+        Objects.requireNonNull(source, "source");
+        Objects.requireNonNull(target, "target");
+        long copied = 0L;
         CharBuffer buffer = CharBuffer.allocate(BUFFER_SIZE);
-        int read;
-        while ((read = source.read(buffer)) > -1) {
+        for (int read; (read = source.read(buffer)) > -1; copied += read) {
 	    buffer.flip();
             target.append(buffer, 0, read);
-            totalRead += read;
         }
-        return totalRead;
+        return copied;
     }
 }
 




More information about the core-libs-dev mailing list