Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: replaced InputStream with FileInputstream; former is abstract

...

This noncompliant snippet intends to read a specific number of bytes from an InputStream a FileInputStream but suffers from a few pitfalls. The objective is to read 1024 bytes and return them as a String. Unfortunately, this won't happen because of the general contract of the read methods.

...

Code Block
bgColor#FFcccc
public static String readBytes(InputStreamFileInputStream in) throws IOException {
  String str = "";
  byte[] data = new byte[1024];
  while (in.read(data) > -1) {
    str += new String(data);
  }
  return str;
}

...

Code Block
bgColor#ccccff
public static String readBytes(InputStreamFileInputStream in) throws IOException {
  int offset = 0;
  int bytesRead = 0;
  byte[] data = new byte[1024];
  while(true) { 
    bytesRead += in.read(data, offset, data.length - offset);
    if(bytesRead == -1 || offset >= data.length)
      break;
    offset += bytesRead;
  }
  String str = new String(data, "UTF-8");
  return str;
}

...