Pages

Saturday, 7 January 2017

Chapter 17 Exercise 17, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

17.17 (BitOutputStream)
Implement a class named BitOutputStream, as shown in Figure 17.22,
for writing bits to an output stream. The writeBit(char bit) method
stores the bit in a byte variable. When you create a BitOutputStream,
the byte is empty. After invoking writeBit('1'), the byte becomes
00000001. After invoking writeBit("0101"), the byte becomes 00010101.
The first three bits are not filled yet. When a byte is full, it is sent
to the output stream. Now the byte is reset to empty. You must close the
stream by invoking the close() method. If the byte is neither empty nor
full, the close() method first fills the zeros to make a full 8 bits in
the byte, and then outputs the byte and closes the stream. For a hint,
see Programming Exercise 5.44. Write a test program that sends the bits
010000100100001001101 to the file named Exercise17_17.dat.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class BitOutputStream implements AutoCloseable {

    FileOutputStream out;
    int bits; // bit buffer
    int bitPos; // bitPos bit index, gets reset when bitPos == 8


    public BitOutputStream(File file) throws IOException {
        out = new FileOutputStream(file);
    }


    /**
     * Writes bit into byte buffer.
     * Byte Buffer writes to file when full
     *
     * @param bit char representing a bit value '1' or '0'
     * @throws IOException
     */
    public void writeBit(char bit) throws IOException {
        bits = bits << 1;

        if (bit == '1')
            bits = bits | 1;

        if (++bitPos == 8) {
            out.write(bits);
            bitPos = 0;
        }

    }


    /**
     * Writes bits into byte buffer.
     * Byte buffer writes to file when full
     *
     * @param bit a string sequence in 1's and 0's
     * @throws IOException
     */
    public void writeBit(String bit) throws IOException {
        for (int i = 0; i < bit.length(); i++)
            writeBit(bit.charAt(i));
    }

    /**
     * Closes BitOutputStream
     * <p>
     * Any remaining bits will get outputted to file
     *
     * @throws IOException
     */
    public void close() throws IOException {


        if (bitPos > 0) {
            bits = bits << 8 - bitPos; // add 0's to end of byte
            out.write(bits);
        }

        out.close();

    }

}

import java.io.File;
import java.io.IOException;

public class Exercise_17 {

    public static void main(String[] args) {

        File file = new File("Exercise17_17.dat");
        String bits = "010000100100001001101";

        try (BitOutputStream out = new BitOutputStream(file)) {

            out.writeBit(bits);

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

No comments:

Post a Comment