Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Confusion on OutputStream write(int b)

Status
Not open for further replies.

VicM

Programmer
Sep 24, 2001
444
US
I'm having some trouble understanding the OutputStream write(int b) method.

When I read the javadoc for this method, it says it 'writes byte b' to the output stream; whether it's the abstract method in OutputStream or the implemented method in, say, FileOutputStream.

So what I don't understand is, if the argument is an integer, and the method writes it as a byte, isn't there a high probability for loss of data when the integer value exceeds what a byte can hold?

Enlightenment is humbly accepted.

Vic
 
Well, that's not probabilistic, the rest of the bytes will be ignored.

From javadoc:

Code:
public abstract void write(int b) throws IOException

Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.

You can test the following code:

Code:
java.io.FileOutputStream fos = new java.io.FileOutputStream(new java.io.File("Test.txt"));
int i =1024*14+ 69;
fos.write(i);
fos.close();

You will get an "E", that is the 69 ASCII code.

Cheers,

Dian
 
Dian

Thanks for the response. So are you saying that when using the write(int b) method, the programmer must take care to ensure that the integer b does not exceed 255?

I can understand on the input side, where the method, read(), reads a byte but returns an integer, that the casting is to a wider data type and therefore no loss of data.

I guess I'm wondering why the Java developers chose to use an integer as the argument to this method when the other write methods use byte arrays. Perhaps this is just one of those quirks of the language. :)

Vic
 
I'm saying nothing, it's all from the Javadocs :p

Anyway, sedj is giving you the answer. If this method doesn't fit you, there are plenty of them to use.

Cheers,

Dian
 
I can understand on the input side, where the method, read(), reads a byte but returns an integer, that the casting is to a wider data type and therefore no loss of data.
That is even common in c/ c++.
The wider return type is used to return a value which indicates EOF: -1.

seeking a job as java-programmer in Berlin:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top