1. /*
  2. * @(#)CheckedInputStream.java 1.14 01/11/29
  3. *
  4. * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util.zip;
  8. import java.io.FilterInputStream;
  9. import java.io.InputStream;
  10. import java.io.IOException;
  11. /**
  12. * An input stream that also maintains a checksum of the data being read.
  13. * The checksum can then be used to verify the integrity of the input data.
  14. *
  15. * @see Checksum
  16. * @version 1.14, 11/29/01
  17. * @author David Connelly
  18. */
  19. public
  20. class CheckedInputStream extends FilterInputStream {
  21. private Checksum cksum;
  22. /**
  23. * Creates an input stream using the specified Checksum.
  24. * @param in the input stream
  25. * @param cksum the Checksum
  26. */
  27. public CheckedInputStream(InputStream in, Checksum cksum) {
  28. super(in);
  29. this.cksum = cksum;
  30. }
  31. /**
  32. * Reads a byte. Will block if no input is available.
  33. * @return the byte read, or -1 if the end of the stream is reached.
  34. * @exception IOException if an I/O error has occurred
  35. */
  36. public int read() throws IOException {
  37. int b = in.read();
  38. if (b != -1) {
  39. cksum.update(b);
  40. }
  41. return b;
  42. }
  43. /**
  44. * Reads into an array of bytes. Will block until some input
  45. * is available.
  46. * @param buf the buffer into which the data is read
  47. * @param off the start offset of the data
  48. * @param len the maximum number of bytes read
  49. * @return the actual number of bytes read, or -1 if the end
  50. * of the stream is reached.
  51. * @exception IOException if an I/O error has occurred
  52. */
  53. public int read(byte[] buf, int off, int len) throws IOException {
  54. len = in.read(buf, off, len);
  55. if (len != -1) {
  56. cksum.update(buf, off, len);
  57. }
  58. return len;
  59. }
  60. /**
  61. * Skips specified number of bytes of input.
  62. * @param n the number of bytes to skip
  63. * @return the actual number of bytes skipped
  64. * @exception IOException if an I/O error has occurred
  65. */
  66. public long skip(long n) throws IOException {
  67. byte[] buf = new byte[512];
  68. long total = 0;
  69. while (total < n) {
  70. long len = n - total;
  71. len = read(buf, 0, len < buf.length ? (int)len : buf.length);
  72. if (len == -1) {
  73. return total;
  74. }
  75. total += len;
  76. }
  77. return total;
  78. }
  79. /**
  80. * Returns the Checksum for this input stream.
  81. */
  82. public Checksum getChecksum() {
  83. return cksum;
  84. }
  85. }