title: Writing Bits to a file using BitSet & FileOutputStream
body: <p>I've run into a bit of a problem when it comes to writing specific bits to a file. I apologise if this is a duplicate of anything but I could not find a reasonable answer with the searches I ran.</p>
  
  <p>I have a number of difficulties with the following:</p>
  
  <ol>
  <li><p>Writing a header (Long) bit by bit (converted to a byte array so the
  FileOutputStream can utilise it) to the file.</p></li>
  <li><p>Writing single bits to the file. For example, at one stage I am required to write a single bit set to 0 to the file so my initial thought would be to use a BitSet but Java seems to treat this as a null? </p>
  
  <pre><code>BitSet initialPadding = new BitSet();
  initialPadding.set(0, false);
  fileOutputStream.write(initialPadding.toByteArray());
  </code></pre></li>
  </ol>
  
  <hr>
  
  <p>1)</p>
  
  <p>I create a FileOutputStream as shown below with the necessary file name:</p>
  
  <pre><code>FileOutputStream fileOutputStream = new FileOutputStream(file.getAbsolutePath());
  </code></pre>
  
  <p>I am attempting to create an ".amr" file so the first step before I perform any bit manipulation is to write a header to the beginning of the file. This has the following value: </p>
  
  <pre><code>Long defaultHeader = 0x2321414d520aL;
  </code></pre>
  
  <p>I've tried writing this to the file using the following method but I am pretty sure it does not write the correct result:</p>
  
  <pre><code>fileOutputStream.write(defaultHeader.byteValue()); 
  </code></pre>
  
  <p>Am I using the correct streams? Are my convertions completely wrong?</p>
  
  <hr>
  
  <p>2) </p>
  
  <p>I have a <code>public BitSet fileBitSet;</code>which has bits read in from a ".raw" file as the input. I need to be able to extract certain bits from the BitSet in order to write them to the file later. I do this using the following method: </p>
  
  <pre><code>public int getOctetPayloadHeader(int startPoint) {
  
      int readLength = 0;
  
      octetCMR = fileBitSet.get(0, 3);
      octetRES = fileBitSet.get(4, 7);
  
      if (octetRES.get(0, 3).isEmpty()) {
  
          /* Keep constructing the payload header. */
  
          octetFBit    = fileBitSet.get(8, 8);
          octetMode    = fileBitSet.get(9, 12);
          octetQuality = fileBitSet.get(13, 13);
          octetPadding = fileBitSet.get(14, 15);
          ... }
  </code></pre>
  
  <p>What would be the best way to go for writing these bits to a file bearing in mind that I may be required to sometimes write a single bit or 81 bits at a particular offset in the <code>fileBitSet</code> ?</p>