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)

4
  • possible duplicate of Binary to text in Java Commented Oct 21, 2014 at 16:25
  • possible duplicate of Convert binary string to byte array Commented Oct 21, 2014 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 Commented Oct 21, 2014 at 16:49
  • read in chunks of 8/16/32 characters Commented Oct 21, 2014 at 16:58

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.