Why is there a write (int b) method for an OutputStream?

Possible duplicate:
Why Java OutputStream.write () accepts integers but writes bytes

Why OutputStream write() method of the OutputStream class take an integer instead of a byte when it actually writes data bytes by a byte?

+6
source share
3 answers

it is consistent with w / IntputStream.read() , and since most operations (sum, mul, div, etc.) are promoted to int, this eliminates the need for constant additions to byte .

I think everything is in order.

+3
source

It actually writes one byte from this int (low 8 bits). See Documentation: http://docs.oracle.com/javase/1.4.2/docs/api/java/io/OutputStream.html#write%28int%29

Change I searched a bit and found this: Why Java OutputStream.write () accepts integers but writes bytes

+1
source

You can use it to write either a signed or unsigned byte. Most byte streams accept unsigned bytes, and the corresponding InputStream.read () reads a non-negative int , which you can use for (byte) to make it signed.


If you create a readObject and writeObject, you will be provided with ObjectInputStream and ObjectOutptuStream to read / write your custom serialization format for your object.

http://java.sun.com/developer/technicalArticles/ALT/serialization/

 private void writeObject(ObjectOutputStream oos) throws IOException { oos.defaultWriteObject(); // Write/save additional fields oos.write(byteField); oos.writeObject(new java.util.Date()); } // assumes "static java.util.Date aDate;" declared private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); // Read/initialize additional fields byteField = oos.read(); aDate = (java.util.Date)ois.readObject(); } 
0
source

Source: https://habr.com/ru/post/903531/


All Articles