0

I want to write the file as byte only and not the character.

String binaryString = "10110101"

I am using

byte mybyte  = Byte.parseByte(binaryString,2);

I want to write this converted byte into the file as a byte and not the character.

I am using :

FileOutputStream fos1 = new FileOutputStream(new File("output"));
fos.write(mybyte);

But after write, when I see the files the byte is actually written as the characters.

Is I am doing something wrong in conversion ? How to make it write as byte and not char ?

Edit:

Like for the String 101101010111001011111000 (taking 8 bits at a time and then writing to the file) : it is converted to "Z9|".

13
  • 1
    "But after write, when I see the files the byte is actually written as the characters." - how are you "seeing" that? A short but complete program demonstrating the problem would help. Commented Jan 22, 2014 at 14:05
  • 1
    (In fact, Byte.parseByte will throw an exception for that input...) Commented Jan 22, 2014 at 14:07
  • @ Jon Skeet This is the problem that when I open the file with such byte written they are just appearing as a Character so I can see them Commented Jan 22, 2014 at 14:11
  • You "open" it with a text editor? Commented Jan 22, 2014 at 14:11
  • 1
    How did you "try the terminal window"? Like "less" or something? You really need a tool that displays HEX. Commented Jan 22, 2014 at 14:20

1 Answer 1

1

You actually write the binary data 10110101 to the file, but when you open that file in a text editor it will be displayed as a character.

If you want to write text that represent the given number (e.g. in decimal form), use a Writer:

FileOutputStream fos1 = new FileOutputStream(new File("output"));
OutputStreamWriter w = new OutputStreamWriter(fos1, StandardCharsets.UTF_8);
w.write(""+mybyte); // ""+mybyte creates a string with the decimal representation of mybyte
Sign up to request clarification or add additional context in comments.

3 Comments

The Decimal representation will be converted into the character and we loose the actual byte.
@Gaurav this code e.g. writes the characters 105 (3 bytes) to the file instead of writing a byte like your code does. If you want an actual byte then your code is already correct (ignoring the signed bytes issue), you just have to open the file in a hex editor or similar.
I don't want all the bytes at same time, I want the data represented byte by byte in the file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.