title: write object to file java
body: <p>I am creating an application that manages an agenda. Each contact must be written in the object file. How can I check if the file exists and is there a way to write the next object without overwriting??</p>
  
  <h2>My class:</h2>
  
  <pre><code>import java.io.*;
  
  public class WriteFile {
      public void setContact(Agenda contact){
          ObjectOutputStream out;
  
          try{
              File file = new File("Contacts.txt");
              out = new ObjectOutputStream(new FileOutputStream(file));
              out.writeObject(contact);
  
  
              out.flush();
              out.close();
              System.out.println("Object written to file");
          }
          catch (FileNotFoundException ex) {
              System.out.println("Error with specified file") ;
              ex.printStackTrace();
          }
          catch (IOException ex) {
              System.out.println("Error with I/O processes") ;
              ex.printStackTrace();
          }             
      }
  
  }
  </code></pre>