Guest User

Untitled

a guest
Oct 22nd, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. package com.study.io;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5.  
  6. public class BufferedInputStream extends InputStream {
  7. private InputStream inputStream;
  8. private byte[] buffer = new byte[1024];
  9. private int index;
  10. private int count;
  11.  
  12. public BufferedInputStream(InputStream inputStream) {
  13. this.inputStream = inputStream;
  14. }
  15.  
  16. @Override
  17. public int read() throws IOException {
  18. if (checkBuffer() == -1) {
  19. return -1;
  20. }
  21. int value = buffer[index];
  22. index++;
  23.  
  24. return value;
  25. }
  26.  
  27. private int checkBuffer() throws IOException {
  28. if (index == count) {
  29. count = inputStream.read(buffer);
  30. index = 0;
  31. }
  32. return count;
  33. }
  34. @Override
  35. public int read(byte[] b) throws IOException {
  36. return read(b, 0, b.length);
  37. }
  38.  
  39. @Override
  40. public int read(byte[] b, int off, int len) throws IOException {
  41. int destIndex = off;
  42. while(destIndex < off + len){
  43. if (checkBuffer() == -1) {
  44. return -1;
  45. }
  46. int bufferRest = count - index;
  47. int destRest = off + len - destIndex;
  48. int bytesAmount = Math.min(bufferRest, destRest);
  49. System.arraycopy(buffer, index, b, destIndex, bytesAmount);
  50. index += bytesAmount;
  51. destIndex += bytesAmount;
  52. if(destIndex == off + len){
  53. return destIndex - off;
  54. }
  55. }
  56. return destIndex - off;
  57. }
  58.  
  59. @Override
  60. public void close() throws IOException {
  61. inputStream.close();
  62. }
  63. }
Add Comment
Please, Sign In to add comment