6
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.
Philipp Reichart
  • 20,771
  • 6
  • 58
  • 65
John Cooper
  • 7,343
  • 31
  • 80
  • 100

6 Answers6

10
  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

ratchet freak
  • 47,288
  • 5
  • 68
  • 106
7

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.

home
  • 12,468
  • 5
  • 46
  • 54
4

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

Philipp Reichart
  • 20,771
  • 6
  • 58
  • 65
  • 1
    Are you sure (2) is correct? Where does the API for close() guarantee that all outstanding bytes will be flushed? – Paul Grime Sep 04 '11 at 17:25
  • There's little documentation, mostly personal experience -- most streams will `flush()` on closing them, like [FilterOutputStream](http://download.oracle.com/javase/6/docs/api/java/io/FilterOutputStream.html#close()) which most others extend and [ObjectOutputStream](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/io/ObjectOutputStream.java#ObjectOutputStream.close%28%29) and they all dutifully implement `flush()`, with the notably exception of [GZIPOutputStream](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4813885). – Philipp Reichart Sep 04 '11 at 17:41
  • @PaulGrime See `FilterOutputStream.close()`. – user207421 Jul 02 '18 at 08:29
2
  1. You use flush() to clear the internal buffers(if any) and force write(i.e. flush) all the pending data in to the stream destination.
  2. close() method is used to close the stream, once called, you can't use the stream any more.
  3. No. You are reading "a John object from a file". An object of type John should have been previously serialized in to the file.
  4. There are many alternatives to Java serialization such as XStream. See this SO answer for alternatives to serialization.
Community
  • 1
  • 1
Suraj Chandran
  • 24,433
  • 12
  • 63
  • 94
1

1) To make sure any possible buffered bytes are written. See java.io.OutputStream.flush().

2) Not sure what you mean, but calls to close() should be placed in a finally block to ensure the resource is closed. Quick Google reveals - article.

3) You are not reading a file object. You are reading a previously serialized Java object from a file. Hopefully this object will be of type John, else you will get a ClassCastException. It will be of type John, as you previously called "oos.writeObject(myObj)" where myObj is of type John.

4) Google for serializing Java objects. There are many libraries for serializing Java objects to binary files, xml, json, etc, etc. The JDK itself comes with one called XMLEncoder.

Paul Grime
  • 14,970
  • 4
  • 36
  • 58
1
  1. when to use flush:

Flush function is to explicitly ask Java program to write something into the disk, which means doing IO. Say if we are using a bufferedOutputStream, when we do write("something"), it is stored in the buffer, but not in the disk yet. When you call flush, it will write the stuffs in your buffer to the disk. Usually, you don't need to call the flush by yourself, cause it requires IO and lower down the speed. The stream will automatically flush when the buffer is full. Unless you want some contents being updated to the disk, you can use flush.

  1. Sorry, didn't understand your question? which score?

  2. This is what serialization does, it allows you to store some object into your file system and get it back. You are reading the byte stream and convert it back to the object.

  3. There are lot of ways (xml, database, txt file), write your own format to store your data in a local file, or store them in a database. Let me just use your example John here. It has name and department attributes. You can write a format output which takes a John instance, and do the following stuff.

    outputStream.write("class John\n"); outputStream.write("toString: "+instance+"\n"); outputStream.close();

Then it will save as a local txt file which you can open it and read it.

ausgoo
  • 247
  • 1
  • 10