Question: instructions for students: You don't need this part: System.out.println( Confirming Write, reading the file...); Scanner input = new Scanner(new File(testOutput.dat)); while (input.hasNextLine()) { String line
instructions for students:
You don't need this part:
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();
Make sure the class with the main program has the same name as the Java source file that contians i, the code below.
THIS IS CODE:
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Scanner;
/** * * @author michael */ public class Program2 {
/** * * @param b * @return */ public static String byteString(Byte b) { return String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0'); }
/** * * @param args * @throws Exception */ 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;
/** * * @param file * @throws IOException */ public BitOutputStream(File file) throws IOException { output = new FileOutputStream(file); bitsWritten = 0; currentByte = 0; }
/** * * @param bitString * @throws IOException */ public void writeBit(String bitString) throws IOException { for (int i = 0; i < bitString.length(); ++i) { writeBit(bitString.charAt(i)); } }
/** * * @param bit * @throws IOException */ 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; } }
/** * * @throws IOException */ 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
