Showing posts with label FileInputStream. Show all posts

How to read Properties file from resource folder in Java?

What is Properties file?
Properties file used for configurable parameters of your application/project like database host, username and password.

Scenario
For security reason you've to change your database password weekly or monthly. Consider if you assign password in variable[hard coded] of your program then you've to shut down the whole system and start all over again, Its not feasible when you are dealing with production environment(live server), you can't shut down live server. In that case .properties files help you to deal with this kinda situation. When you change value in .properties file you don't have to restart the system. Program will read the updated value.

common.properties
Create resource folder in your project and add common.properties file in it. [How to create resource folder in Netbeans?]
#Database credentials
host=localhost
username=root
password=root

Source code up-to JDK 1.6 (ReadPropertiesFile.java)
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class ReadPropertiesFile {

    /* Create basic object */
    ClassLoader objClassLoader = null;
    Properties commonProperties = new Properties();
    
    public ReadPropertiesFile() {
        /* Initialize 'objClassLoader' once so same object used for multiple files. */
        objClassLoader = getClass().getClassLoader();
    }
    
    public String readKey(String propertiesFilename, String key){
        /* Simple validation */
        if (propertiesFilename != null && !propertiesFilename.trim().isEmpty()
                && key != null && !key.trim().isEmpty()) {
            /* Create an object of FileInputStream */
            FileInputStream objFileInputStream = null;
            
            /**
             * Following try-catch is used to support upto 1.6.
             * Use try-with-resource in JDK 1.7 or above
             */
            try {
                /* Read file from resources folder */
                objFileInputStream = new FileInputStream(objClassLoader.getResource(propertiesFilename).getFile());
                /* Load file into commonProperties */
                commonProperties.load(objFileInputStream);
                /* Get the value of key */
                return String.valueOf(commonProperties.get(key));
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }finally{
                /* Close the resource */
                if(objFileInputStream != null){
                    try {
                        objFileInputStream.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
    
    public static void main(String[] args) {
        /* Create object of ReadResourceFile */
        ReadPropertiesFile objPropertiesFile = new ReadPropertiesFile();
        
        /* Will give you 'null' in case key not available */
        System.out.println("Database Driver: "+ objPropertiesFile.readKey("common.properties", "dbdriver"));
        
         /* Read values from resource folder */
        System.out.println("Host: "+ objPropertiesFile.readKey("common.properties", "host"));
        System.out.println("Username: "+ objPropertiesFile.readKey("common.properties", "username"));
        
        try {
            while (true) {      
                /* Print the password from commom.properties file */
                System.out.println("Password: "+ objPropertiesFile.readKey("common.properties", "password"));
                
                /* Put the current thread in sleep for 5 seconds and change the value of 'password' */
                Thread.sleep(5000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Source code JDK 1.7 or above (ReadPropertiesFile.java)
Using try-with-resource in Java 1.7 or above
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class ReadPropertiesFile {

    /* Create basic object */
    ClassLoader objClassLoader = null;
    Properties commonProperties = new Properties();
    
    public ReadPropertiesFile() {
        /* Initialize 'objClassLoader' once so same object used for multiple files. */
        objClassLoader = getClass().getClassLoader();
    }
    
    public String readKey(String propertiesFilename, String key){
        if (propertiesFilename != null && !propertiesFilename.trim().isEmpty()
                && key != null && !key.trim().isEmpty()) {
            /* try-with-resource in JDK 1.7 or above */
            try(
                    FileInputStream objFileInputStream = new FileInputStream(objClassLoader.getResource(propertiesFilename).getFile());
               ){
                /* Load file into commonProperties */
                commonProperties.load(objFileInputStream);
                /* Get the value of key */
                return String.valueOf(commonProperties.get(key));
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }
    
    public static void main(String[] args) {
       /* Create object of ReadResourceFile */
        ReadPropertiesFile objPropertiesFile = new ReadPropertiesFile();
        
        /* Will give you 'null' in case key not available */
        System.out.println("Database Driver: "+ objPropertiesFile.readKey("common.properties", "dbdriver"));
        
         /* Read values from resource folder */
        System.out.println("Host: "+ objPropertiesFile.readKey("common.properties", "host"));
        System.out.println("Username: "+ objPropertiesFile.readKey("common.properties", "username"));
        
        try {
            while (true) {      
                /* Print the password from commom.properties file */
                System.out.println("Password: "+ objPropertiesFile.readKey("common.properties", "password"));
                
                /* Put the current thread in sleep for 5 seconds and change the value of 'password' */
                Thread.sleep(5000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output
Database Driver: null
Host: localhost
Username: root
Password: root
Password: root
Password: admin123
References
How to create resource folder in Netbeans?

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 read file using FileInputStream in Java?

Java 1.6 or less
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadFileInputStreamExample {
    
    public static void main(String[] args) {
        /* Create object of File. */
        File objFile = new File("D:\\Readme.txt");

        /* Create object of FileInputStream */
        FileInputStream objFileInputStream = null;
        try {
            /**
             * A FileInputStream obtains input bytes from a file in a file system. What files
             * are available depends on the host environment.
             *
             * FileInputStream is meant for reading streams of raw bytes
             * such as image data. For reading streams of characters, consider using
             * FileReader.
             */
            objFileInputStream = new FileInputStream(objFile);
            
            /* Read content of File. */
            int byteOfData;
            while ((byteOfData = objFileInputStream.read()) != -1) {
                /* Print content of File. */
                System.out.print((char) byteOfData);
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            /* Close the FileInputStream */
            if (objFileInputStream != null) {
                try {
                    objFileInputStream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}

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

public class ReadFileInputStreamExample {
    
    public static void main(String[] args) {
        /* Create object of File. */
        File objFile = new File("D:\\Readme.txt");
        
        try (
                /**
                 * A FileInputStream obtains input bytes from a file in a file system. What files
                 * are available depends on the host environment.
                 *
                 * FileInputStream is meant for reading streams of raw bytes
                 * such as image data. For reading streams of characters, consider using
                 * FileReader.
                 */
                FileInputStream objFileInputStream = new FileInputStream(objFile);
            ) {
            /* Read content of File. */
            int byteOfData;
            while ((byteOfData = objFileInputStream.read()) != -1) {
                /* Print content of File. */
                System.out.print((char) byteOfData);
            }
        } 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/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