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