title: How to write binary to a file in Java
body: <p>I am trying to get input from a file, convert the characters to binary and then output the binary to another output file.</p>
  
  <p>I used Integer.toBinaryString() in order to make the conversion.</p>
  
  <p>Everything is working as it should but for some reason nothing is written to the output file, but when I use System.out.println() it outputs fine.</p>
  
  <pre><code>import java.io.*;
  
  public class Binary {
  
      FileReader fRead = null;
      FileWriter fWrite = null;
      byte[] bFile = null;
      String fileIn;
  
      private String binaryString(int bString) {
  
          String binVal = Integer.toBinaryString(bString);
  
          while (binVal.length() &lt; 8) {
              binVal = "0" + binVal;
          }
  
          return binVal;
      }
  
      public void input() throws IOException, UnsupportedEncodingException {
          try {
              fRead = new FileReader("in.txt");
              BufferedReader reader = new BufferedReader(fRead);
  
              fileIn = reader.readLine();
              bFile = fileIn.getBytes("UTF-8");
  
              fWrite = new FileWriter("out.txt");
              BufferedWriter writer = new BufferedWriter(fWrite);
  
              for (byte b: bFile) {
                  writer.write(binaryString(b));
                  System.out.println(binaryString(b));
              }
              System.out.println("Done.");
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
  
      public Binary() {
  
      }
  
      public static void main(String[] args) throws UnsupportedEncodingException, IOException {
          Binary b = new Binary();
          b.input();
      }
  
  }
  </code></pre>
  
  <p>I know my code is not very good, I'm relatively new to Java so I don't know many others ways to accomplish this.</p>