How to read file in Java?

UPDATED: 03 August 2014
Following is very common method to read any file in Java, However certain file type has their own formatting . It will not work in case of XML, PDF, Microsoft Excel, Microsoft Word, etc... There are bunch of APIs available on Internet that could help to read / parse this files.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class ReadFile {
    public static void main(String[] args) {
        /* Create an object of File and specify file path */
        File file = new File("D:\\Dropbox\\Workspace\\SampleTextFile.txt");
        /* String to hold new line value from file */
        String fileLine = "";
        /* Check if file is exists or not */
        if(file.exists()){
            /* Check you have permission to read file or not */
            if(file.canRead()){
                try {
                    /* BufferedReader to read file line by line */
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    /* Loop until last line of file */
                    while((fileLine = br.readLine())!= null){
                        /* Print the line of file */
                        System.out.println(fileLine);
                    }
                } catch (Exception ex) {
                    /* Runtime exception */
                    ex.printStackTrace();
                }
            }else{
                /* Show message you don't have permission to read the file */
                System.out.println("Don't have permission to read the file.");
            }
        }else{
            /* Show message file doesn't exsists the specified location. */
            System.out.println("Can't find file specified");
        }
    }
}

Other References:
How to write file in Java?
How to append text to an existing file in Java?
How to read/parse XML file in Java?

0 comments :