When to use flush() in java?

前端 未结 6 1784
长发绾君心
长发绾君心 2020-12-14 04:53
import java.io. * ;
public class Ser {

    public static void main(String args[]) {

        try {
            John myObj = new John(\"Sachin\", \"Cricket\");
              


        
6条回答
  •  感情败类
    2020-12-14 05:23

    have a few questions in the above example.

    1. When to use flush method and why do we use it?

      You usually won't need to flush() and OutputStream, it won't lose any data if you properly close() it in the end. Sometimes, you want to communicate to the underlying data sink (e.g. network Socket, local File, or another OutputStream) that you want any data written to the stream to be flushed/processed -- but as per the flush() API doc, that's not guaranteed to happen.

    2. What does close method carry a score here?

      I really don't understand this part, but the close() closes an OutputStream and causes it to write out any data it still has buffered -- so there's no need to call flush() before close(). An OutputStream can not be written to after it has been closed.

    3. myObj2 = (John) ois.readObject(); ... please correct me if i am wrong, i am reading the file object and storing into another object and typecasting the file object.

      Wrong, you're reading from the ObjectInputStream ois, it's irrelevant where it has its data from (in your case it does, indeed, come from a file, but there's no "file object" in your code).

      ObjectInputStream can reconstruct any data previously written/serialized by ObjectOutputStream -- so in this case you de-serialize a previously serialized object of type John. Because serialization only works on some Java types (primitives and implementors of Serializable), it doesn't know about your specific class John. But you know, you previously serizalized a John object, so you can safely cast from Object to John and assign it to a local variable.

    4. What are the alternatives of Serialization or persisting the data in Java. I don't want the data to get into file as byte stream.

      You could look into other serialization/marshalling approaches like XStream, JSON or roll your own (complex, only do this if you have a good reason). Most of these will prove more complex than the built-in serialization, so be sure you have a good reason to not just write "itno file as byte stream".

提交回复
热议问题