1

I stored bytes within a string in Java

String header ="00110011000000011001000000000001001011000000000100000010000000000000000000000000000000000000000000000000000000000000000000000000";

Now i want to write that String to a file, but export that as a series of bits and not encoded as a text. Writing to the file looks like this:

BufferedWriter writer = new BufferedWriter (new FileWriter("test.epd"));
writer.write(header);

How can I do this(The string in this prog will be longer --> around 8kB)

valentin
  • 86
  • 6
  • possible duplicate of [Binary to text in Java](http://stackoverflow.com/questions/4211705/binary-to-text-in-java) – ProgramFOX Oct 21 '14 at 16:25
  • possible duplicate of [Convert binary string to byte array](http://stackoverflow.com/questions/17727310/convert-binary-string-to-byte-array) – fvu Oct 21 '14 at 16:31
  • @fvu But his string is just 16bit long so he can use a variable to store the string .. In my case no variable will be long enough! As i said i need about 8kB – valentin Oct 21 '14 at 16:49
  • read in chunks of 8/16/32 characters – fvu Oct 21 '14 at 16:58

1 Answers1

1

I would use BinaryCodec from commons apache commons-codec.

String headerb = "00110011000000011001000000000001001011000000000100000010000000000000000000000000000000000000000000000000000000000000000000000000";
BinaryCodec codec = new BinaryCodec();
//I have no idea why this method is not static. 
//you may  use BinaryCodec.fromAscii(ascii.toCharArray()) instead
byte[] bval = codec.toByteArray(headerb);
File file = new File("test.epd");
Files.write(bval, file );

//Test that when the file is read, we retrieve the same string
byte[] byteArray = Files.toByteArray(file);
String asciiString = BinaryCodec.toAsciiString(byteArray);
System.out.println(asciiString);
Xavier Delamotte
  • 3,519
  • 19
  • 30