Advertisement
zubayer007

Object Write and Read

Sep 26th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.30 KB | None | 0 0
  1. import java.io.EOFException;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.ObjectInputStream;
  7. import java.io.ObjectOutputStream;
  8. import java.io.OutputStream;
  9.  
  10. public class Test{
  11.     private static String filename = "test";
  12.  
  13.     public static void main(String[] args) {
  14.         writeToBinary (filename, "a", true);
  15.         writeToBinary (filename, "b", true);
  16.         writeToBinary (filename, "c", true);
  17.         readFromBinaryFile (filename);
  18.     }
  19.  
  20.     public static void writeToBinary (String filename, Object obj, boolean append){
  21.         File file = new File (filename);
  22.         ObjectOutputStream out = null;
  23.  
  24.         try{
  25.             if (!file.exists () || !append) out = new ObjectOutputStream (new FileOutputStream (filename));
  26.             else out = new AppendableObjectOutputStream (new FileOutputStream (filename, append));
  27.             out.writeObject(obj);
  28.             out.flush ();
  29.         }catch (Exception e){
  30.             e.printStackTrace ();
  31.         }finally{
  32.             try{
  33.                 if (out != null) out.close ();
  34.             }catch (Exception e){
  35.                 e.printStackTrace ();
  36.             }
  37.         }
  38.     }
  39.  
  40.     public static void readFromBinaryFile (String filename){
  41.         File file = new File (filename);
  42.  
  43.         if (file.exists ()){
  44.             ObjectInputStream ois = null;
  45.             try{
  46.                 ois = new ObjectInputStream (new FileInputStream (filename));
  47.                 while (true){
  48.                     String s = (String)ois.readObject ();
  49.                     System.out.println (s);
  50.                 }
  51.             }catch (EOFException e){
  52.  
  53.             }catch (Exception e){
  54.                 e.printStackTrace ();
  55.             }finally{
  56.                 try{
  57.                     if (ois != null) ois.close();
  58.                 }catch (IOException e){
  59.                     e.printStackTrace ();
  60.                 }
  61.             }
  62.         }
  63.     }
  64.  
  65.     private static class AppendableObjectOutputStream extends ObjectOutputStream {
  66.           public AppendableObjectOutputStream(OutputStream out) throws IOException {
  67.             super(out);
  68.           }
  69.  
  70.           @Override
  71.           protected void writeStreamHeader() throws IOException {}
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement