Advertisement
Guest User

Untitled

a guest
Feb 25th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.io.IOException;
  4.  
  5.  
  6. /**
  7. * This class can be used to write individual bits to a file.
  8. *
  9. * The close() method must be called to terminate the file properly.
  10. *
  11. * If the number of bits writen is not a multiple of 8, the final byte is only
  12. * partially used. Therefore the number of "real" data bits in the last byte is
  13. * appended to the file just before it is closed.
  14. *
  15. * @author Even Åby Larsen
  16. * @version 1.0
  17. */
  18. public class FileBitSink implements BitSink
  19. {
  20. private FileOutputStream out;
  21. private int buffer;
  22. private int numBits;
  23.  
  24. /**
  25. * Open file f for writing bits.
  26. */
  27. public FileBitSink(File f) throws IOException {
  28. out = new FileOutputStream(f);
  29. }
  30.  
  31. /**
  32. * Write one bit
  33. * @throws java.io.IOException
  34. */
  35. @Override
  36. public void writeBit(int bit) throws IOException {
  37. if (bit != 0 && bit != 1)
  38. throw new IOException("Bit value not 0 or 1: " + bit);
  39.  
  40. buffer = buffer | (bit << numBits);
  41. numBits++;
  42. if (numBits == 8) {
  43. // buffer is full - write to file
  44. out.write((byte) buffer);
  45. numBits = 0;
  46. buffer = 0;
  47. }
  48. }
  49.  
  50. /**
  51. * Writes the final bits and closes the file
  52. * @throws java.io.IOException
  53. */
  54. @Override
  55. public void close() throws IOException {
  56. if (numBits > 0) {
  57. // write the buffer
  58. out.write((byte) buffer);
  59. // and the number of real bits in the final byte
  60. out.write((byte) numBits);
  61. }
  62. // buffer has just been flushed so all 8 bits are used
  63. else
  64. out.write((byte) 8);
  65. out.close();
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement