PrintStream write() method in Java

1.9k views Asked by At

Directly from this Java API:

write

public void write(int b)

Writes the specified byte to this stream. If the byte is a newline and automatic flushing is enabled then the flush method will be invoked.

Note that the byte is written as given; to write a character that will be translated according to the platform's default character encoding, use the print(char) or println(char) methods.

I see it's specified the byte is written as given; However if I try to write(65) I get the A I expected.

What should I write in write() in order to not match the same as it would be with print()? Could you do any example?

3

There are 3 answers

0
Sotirios Delimanolis On

Binary 01000001 (the byte) is the ASCII character A so you get that when you read as a String.

You would need to use FilterOutputStream.html#write(byte[])

write("65".getBytes());

to get the same output.

Or whatever type you need

write(new Integer(65).toString().getBytes());

What should I write in write() in order to not match the same as it would be with print()? Could you do any example?

System.out.println(65); // writes 65 as a String, String.valueOf(65).getBytes()
System.out.write(65); // writes 65 as a byte
System.out.flush();

prints

65 // the String value '65'
A // the character value of binary 65

Read the javadoc for the print methods. The one above accepts an int and

Prints an integer. The string produced by String.valueOf(int) is translated into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

In either case, bytes are written to the stream, but how they are displayed depends on the how your read them. String has constructors that accept a charsetName or Charset object. A Charset (as a concept and as a class) is

A named mapping between sequences of sixteen-bit Unicode code units and sequences of bytes.

0
Cruncher On

given

String s = "some string";
byte[] sData = s.getBytes();

write(sData, 0, sData.length); and print(s);

should be equivilent.

0
Michael Piefel On

If you try

writer.print('Ä');

you might get varying results depending on your platform. It might be a single byte for a platform with Latin-1 as default encoding, or 2 bytes for a platform with UTF-8.