Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use flush() in java?

import java.io. * ;
public class Ser {

    public static void main(String args[]) {

        try {
            John myObj = new John("Sachin", "Cricket");
            System.out.println(myObj);
            FileOutputStream fos = new FileOutputStream("FileName");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(myObj);
            oos.flush();
            oos.close();
        } catch (Exception e) {
            System.out.println("Expection" + e);
            System.exit(0);
        }

        try {
            John myObj2;
            FileInputStream fis = new FileInputStream("FileName");
            ObjectInputStream ois = new ObjectInputStream(fis);
            myObj2 = (John) ois.readObject();
            ois.close();
            System.out.println("New Object" + myObj2);
        } catch (Exception e) {
            System.out.println("Expection" + e);
            System.exit(0);
        }

    }
}

class John implements Serializable {

    private String name;
    private String department;

    public John(String name, String department) {
        this.name = name;
        this.department = department;
    }

    public String toString() {
        return "Name" + name + " " + "Department" + department;

    }

}

I have a few questions in the above example.

  1. When to use flush method and why do we use it?
  2. What does close method carry a score here?
  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.
  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.
like image 768
John Cooper Avatar asked Sep 04 '11 16:09

John Cooper


3 Answers

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

This is used when there needs to be synchronous sending

For example you have a duplex (2-way) connection and you just sent a message and now need to wait for the reply on it, without flush a buffered outputstream might hold it until the buffer fills up (deadlock)

  1. 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 read some data from the stream typecast it into a John (which will throw if the object read wasn't a John)

  1. 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 can write it as text (write out the fields as text on a line) and provide a method to parse it into an object

like image 148
ratchet freak Avatar answered Oct 20 '22 19:10

ratchet freak


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

It flushes anything which is still buffered by the OutputStream. A detailed description is available in JavaDoc.


What does close method carry a score here?

I'm not sure what you mean by 'carry a score', but the close method finally closes resources (Input or Output), it releases e.g. file handles. You should always call close in a finally block to clean up all references the OS may have.

InputStream is = null;
try {
    is = new FileInputStream(...);
    // do stuff
} catch (IOException e) {
    // do stuff
} finally {
    if (is != null) {
        is.close();
    }
}

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.

Somehow correct, you deserialize an Object writen to the file before. Those files are proprietary and can only be understood by Java, so you last question is a good one!


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 have a number of options. For client application you may want to use XML, JSON, or a lightweight database like SQLlite. On server-side you may have a look at more robust databases (e.g. MySQL) as well.

like image 26
home Avatar answered Oct 20 '22 19:10

home


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".

like image 28
Philipp Reichart Avatar answered Oct 20 '22 20:10

Philipp Reichart