Showing posts with label FileReader. Show all posts

How to read file in Java?

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.


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 */
            /* Check you have permission to read file or not */
                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 */
                } catch (Exception ex) {
                    /* Runtime exception */
                /* Show message you don't have permission to read the file */
                System.out.println("Don't have permission to read the file.");
            /* 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?