Showing posts with label FileOutputStream. Show all posts

How to copy file in Java using FileInputStream and FileOutputStream?

This excerpt shows how you can copy content of source file to destination file using java.io.FileInputStream and java.io.FileOutputStream.

Source Code (Java 1.6 or less)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFileExample {

    public static void main(String[] args) {
        /* Create object of File for source file */
        File sourceFile = new File("D:\\Readme.txt");
        /* Create object of File for destination file */
        File destinationFile = new File("D:\\CopyReadme.txt");

        /* Create object of FileInputStream */
        FileInputStream objFileInputStream = null;
        /* Create object of FileOutputStream */
        FileOutputStream objFileOutputStream = null;

        /* Check if source file is exists or not */
        if (sourceFile.exists()) {
            try {
                /* Obtain FileInputStream of source file */
                objFileInputStream = new FileInputStream(sourceFile);

                /* Create destination file if not exists */
                if (!destinationFile.exists()) {
                    destinationFile.createNewFile();
                }

                /* Obtain FileOutputStream of destination file */
                objFileOutputStream = new FileOutputStream(destinationFile);
                
                /* Read content from source File. */
                int byteOfData;
                while ((byteOfData = objFileInputStream.read()) != -1) {
                    /* Write content to destination File. */
                    objFileOutputStream.write(byteOfData);
                }
                System.out.println("File Copied!");
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                /* Close FileInputStream and FileOutputStream */
                try {
                    if (objFileInputStream != null) {
                        objFileInputStream.close();
                    }

                    if (objFileOutputStream != null) {
                        objFileOutputStream.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        } else {
            System.out.println("Source file not found!");
        }
    }
}

Source Code (Java 1.7 or above)(try-with-resources
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFileExample {

    public static void main(String[] args) {
        /* Create object of File for source file */
        File sourceFile = new File("D:\\Readme.txt");
        /* Create object of File for destination file */
        File destinationFile = new File("D:\\CopyReadme.txt");

        /* Check if source file is exists or not */
        if (sourceFile.exists()) {

            /* Create destination file if not exists */
            if (!destinationFile.exists()) {
                try {
                    destinationFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            try (
                    /* Create object of FileInputStream */
                    FileInputStream objFileInputStream = new FileInputStream(sourceFile);
                    /* Create object of FileOutputStream */
                    FileOutputStream objFileOutputStream = new FileOutputStream(destinationFile);
                ) {
                    /* Read content from source File. */
                    int byteOfData;
                    while ((byteOfData = objFileInputStream.read()) != -1) {
                        /* Write content to destination File. */
                        objFileOutputStream.write(byteOfData);
                    }
                    System.out.println("File Copied!");
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Other References:
What is try-with-resources in Java 7 or above?
How to read file in Java?
How to read file using FileInputStream in Java?
How to read/parse XML file in Java?
How to write file in Java?
How to append text to an existing file in Java?

How to Serialize and Deserialize object in Java?


javadoc
To serialize an object means to convert its state to a byte stream so way that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable.

Deserialization is the process of converting the serialized form of an object back into a copy of the object.

Source Code (User.java)
Any object that implements Serializable interface is eligible for Object Serialization.
import java.io.Serializable;

public class User implements Serializable{
    private transient long id;
    private String Firstname;
    private transient String Lastname;
    private transient boolean status;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getFirstname() {
        return Firstname;
    }

    public void setFirstname(String Firstname) {
        this.Firstname = Firstname;
    }

    public String getLastname() {
        return Lastname;
    }

    public void setLastname(String Lastname) {
        this.Lastname = Lastname;
    }
    
    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }
}

transient keyword
Any variable or object declared with transient keyword will not be stored in Serialize Object. It will give you default value particular data type.
  • Boolean Data type: transient boolean will give false value in Object Deserialization.
  • Numeric Data types: transient int, double, long, float will give 0 value in Object Deserialization.
  • String Data type: transient String will give null value in Object Deserialization.
  • Any Object: transient ANY_OBJECT will give null value in Object Deserialization.

Source Code (SerializeObject.java)
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializeObject {
    public static void main(String[] args) {
        System.out.println("Object Serialization Code...");
        /* Creating an object of User */
        User objUser = new User();
        
        /* Set properties of User object */
        /* Id will be set to `0` in serialized object because it is declared as `transient` */
        objUser.setId(111l);
        /* Set Firstname */
        objUser.setFirstname("Vicky");
        /* Lastname will be set to `null` in serialized object because it is declared as `transient` */
        objUser.setLastname("Thakor");
        /* Status will be set to `false` in serialized object because it is declared as `transient` */
        objUser.setStatus(true);
        
        /**
         * try(resource)...catch is supported on Java 7 or above.
         * We don't have to explicitly close the resource. 
         * You can follow same code with closing resources in `finally`.
         */
        try(
                /* Create object of FileOutputStream to store object in file [Windows: C:\Users\CurrentUser\User.ser(i.e: `.ser` Standard File Extension)] */
                FileOutputStream objFileOutputStream = new FileOutputStream(System.getProperty("user.home") + File.separatorChar + "User.ser");
                /* Create object of ObjectOutputStream to write objUser on file. */
                ObjectOutputStream objObjectOutputStream = new ObjectOutputStream(objFileOutputStream);
            ){
            /* Write object on file. */
            objObjectOutputStream.writeObject(objUser);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Source Code (DeSerializeObject)
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeSerializeObject {
    public static void main(String[] args) {
        System.out.println("Object Deserialization Code...");
        /**
         * try(resource)...catch is supported on Java 7 or above.
         * We don't have to explicitly close the resource. 
         * You can follow same code with closing resources in `finally`.
         */
        try(
                /* Create object of FileInputStream to get serialized file. */
                FileInputStream objFileInputStream = new FileInputStream(System.getProperty("user.home") + File.separatorChar + "User.ser");
                /* Create object of ObjectInputStream to read User object from file. */
                ObjectInputStream objObjectInputStream = new ObjectInputStream(objFileInputStream);
           ){
            /* Read the User object from file. We've to cast it to our object */
            User objUser = (User) objObjectInputStream.readObject();
            /* Print the properties of User object */
            System.out.println(objUser.getId());
            System.out.println(objUser.getFirstname());
            System.out.println(objUser.getLastname());
            System.out.println(objUser.isStatus());
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

Output (DeSerializeObject.java)
Object Deserialization Code...
0
Vicky
null
false