When to use flush() in java?

前端 未结 6 1812
长发绾君心
长发绾君心 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:38

    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.

提交回复
热议问题