Uploaded image for project: 'Commons IO'
  1. Commons IO
  2. IO-696

IOUtils.toByteArray throws inconsistent exceptions

    XMLWordPrintableJSON

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 2.9.0
    • Component/s: None
    • Labels:
      None

      Description

      The code of this method is as follows:

      public static byte[] toByteArray(final InputStream input, final int size) throws IOException {        
      
            if (size < 0) {
                  throw new IllegalArgumentException("Size must be equal or greater than zero: " + size);
              }        if (size == 0) {
                  return new byte[0];
              }        final byte[] data = new byte[size];
              int offset = 0;
              int read;        while (offset < size && (read = input.read(data, offset, size - offset)) != EOF) {
                  offset += read;
              }        
              if (offset != size) {
                  throw new IOException("Unexpected read size. current: " + offset + ", expected: " + size);
              }        return data;
          }
      

      When size is below zero, it throws IllegalArgumentException, but when size is not equal to offset, it throws IOException. It is somewhat confusing. It shall throw IOException in both cases, in that both cases check legal sizes. 

        Attachments

          Activity

            People

            • Assignee:
              Unassigned
              Reporter:
              ackelcn ackelcn
            • Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved:

                Time Tracking

                Estimated:
                Original Estimate - Not Specified
                Not Specified
                Remaining:
                Remaining Estimate - 0h
                0h
                Logged:
                Time Spent - 1h 10m
                1h 10m