When to use flush () in Java?
import java.io. * ;
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 several questions in the above example
>When to use the flushing method and why? > What is the score of the close method here? > myObj2 =(John)ois. readObject(); … Please correct me. If I'm wrong, I'm reading a file object, storing it to another object and converting it to a file object. > What are the alternatives to serializing or persisting data using Java I don't want data to enter the file as a byte stream
Solution
It flushes anything that is still buffered by OutputStream Detailed instructions can be found in Javadoc
I'm not sure you mean "with points", but the close method will eventually close the resource (input or output), and it will release, such as a file handle You should always call close in the finally block to clear all references that the operating system may have.
InputStream is = null; try { is = new FileInputStream(...); // do stuff } catch (IOException e) { // do stuff } finally { if (is != null) { is.close(); } }
In some way, you deserialize objects that were previously written to the file These files are proprietary and can only be understood by Java, so your last question is good!
You have many choices For client applications, you may want to use XML, JSON, or lightweight databases such as sqllite On the server side, you can also view more powerful databases (such as MySQL)