Question: The program will compile but will not print out anything and I dont know why import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Scanner; class Program2
The program will compile but will not print out anything and I dont know why
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Scanner;
class Program2 {
public static String byteString(Byte b) { return String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0'); }
public static void main(String[] args) throws Exception { BitOutputStream output = new BitOutputStream(new File("testOutput.dat")); String bitString = "010000100100001001101";
System.out.println(" Writing " + bitString + " to file..."); output.writeBit(bitString); output.close();
System.out.println("Done Writing");
System.out.println(" Confirming Write, reading the file..."); Scanner input = new Scanner(new File("testOutput.dat"));
while (input.hasNextLine()) { String line = input.nextLine().strip(); for (int i = 0; i < line.length(); ++i) { System.out.print(byteString((byte) line.charAt(i)) + " "); } System.out.println(); } System.out.println("Done Reading!"); }
public static class BitOutputStream { private FileOutputStream output;
private byte currentByte; private int bitsWritten;
public BitOutputStream(File file) throws IOException { output = new FileOutputStream(file); bitsWritten = 0; currentByte = 0; }
public void writeBit(String bitString) throws IOException { for (int i = 0; i < bitString.length(); ++i) { writeBit(bitString.charAt(i)); } }
public void writeBit(char bit) throws IOException { if (bit != '0' && bit != '1') { throw new IllegalArgumentException("Bit can only be 1 or 0"); } currentByte = (byte) (currentByte << 1); currentByte += (bit == '0' ? 0 : 1);
if (++bitsWritten >= 8) { output.write(currentByte); currentByte = 0; bitsWritten = 0; } }
public void close() throws IOException {
while (bitsWritten != 0) { writeBit('0'); }
output.close(); } } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
