Javascript required
Skip to content Skip to sidebar Skip to footer

How to Read a File in Html Using File Reader

The Java IO API provides two kinds of interfaces for reading files, streams and readers. The streams are used to read binary data and readers to read graphic symbol data. Since a text file is full of characters, you should be using a Reader implementations to read it. In that location are several ways to read a plain text file in Java e.chiliad. you can utilize FileReader, BufferedReader or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing power.

You lot can also utilise both BufferedReader and Scanner to read a text file line past line in Java. Then Java SE eight introduces another Stream grade coffee.util.stream.Stream which provides a lazy and more efficient mode to read a file.

The JDK vii also introduces a couple of overnice utility due east.g. Files class and try-with-resource construct which made reading a text file, even more, easier.

In this article, I am going to share a couple of examples of reading a text file in Coffee with their pros, cons, and important points well-nigh each approach. This will give you enough item to choose the right tool for the job depending on the size of file, the content of the file, and how you want to read.

1. Reading a text file using FileReader

The FileReader is your general-purpose Reader implementation to read a file. Information technology accepts a Cord path to file or a java.io.File instance to start reading. It too provides a couple of overloaded read() methods to read a graphic symbol or read characters into an assortment or into a CharBuffer object.

Here is an example of reading a text file using FileReader in Java:

            public            static            void            readTextFileUsingFileReader(String            fileName) {            try            {       FileReader textFileReader            =            new            FileReader(fileName);       char[] buffer            =            new            char[8096];            int            numberOfCharsRead            =            textFileReader.read(buffer);            while            (numberOfCharsRead            !            =            -i) {            System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }       textFileReader.close();     }            take hold of            (IOException e) {            // TODO Auto-generated grab cake            eastward.printStackTrace();     }   }  Output Once upon a            time, we wrote a program to read            data            from a            text            file. The plan failed to read a large file only then Java 8 come to rescue, which made reading file lazily using Streams.          

You tin can see that instead of reading one graphic symbol at a time, I am reading characters into an array. This is more efficient because read() will access the file several times merely read(char[]) will admission the file merely in one case to read the same amount of data.

I am using an 8KB of the buffer, so in ane call I am limited to read that much data only. You can accept a bigger or smaller buffer depending upon your heap memory and file size. You should too detect that I am looping until read(char[]) returns -one which signals the end of the file.

Some other interesting thing to notation is to call to Cord.valueOf(buffer, 0, numberOfCharsRead), which is required because you might not have 8KB of data in the file or even with a bigger file, the last call may not exist able to fill up the char array and it could contain dirty information from the last read.

2. Reading a text file in Java using BufferedReader

The BufferedReader grade is a Decorator which provides buffering functionality to FileReader or any other Reader. This grade buffer input from source e.yard. files into retentivity for the efficient read. In the case of BufferedReader, the call to read() doesn't always goes to file if it can detect the data in the internal buffer of BufferedReader.

The default size of the internal buffer is 8KB which is good enough for nigh purpose, just you lot can also increment or decrease buffer size while creating BufferedReader object. The reading code is similar to the previous case.

            public            static            void            readTextFileUsingBufferdReader(String            fileName) {            try            {       FileReader textFileReader            =            new            FileReader(fileName);       BufferedReader bufReader            =            new            BufferedReader(textFileReader);        char[] buffer            =            new            char[8096];            int            numberOfCharsRead            =            bufReader.read(buffer);            // read will be from            // retention            while            (numberOfCharsRead            !            =            -1) {            System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }        bufReader.shut();      }            catch            (IOException e) {            // TODO Auto-generated grab block            e.printStackTrace();     }   }  Output [From File] Java provides several ways to read file

In this case as well, I am reading the content of the file into an array. Instead of reading 1 character at a time, this is more efficient. The but difference between the previous examples and this one is that the read() method of BufferedReader is faster than theread() method of FileReader because read can happen from retention itself.

In order to read the full-text file, you loop until read(char[]) method returns -1, which signals the end of the file. See Cadre Java Book i - Fundamentals to larn more about how BufferedReader grade works in Coffee.

How to read a text file in Java

three. Reading a text file in Java using Scanner

The 3rd tool or form to read a text file in Coffee is the Scanner, which was added on JDK 1.5 release. The other 2 FileReader and BufferedReader are present from JDK i.0 and JDK one.one versions. The Scanner is a much more feature-rich and versatile class.

Information technology does not just provide reading merely the parsing of data equally well. You tin not only read text data merely y'all can likewise read the text as a number or float using nextInt() and nextFloat() methods.

The class uses regular expression blueprint to determine token, which could exist tricky for newcomers. The two main method to read text information from Scanner is side by side() and nextLine(), sometime i read words separated past space while later one tin can be used to read a text file line by line in Java. In most cases, you would apply the nextLine() method as shown beneath:

            public            static            void            readTextFileUsingScanner(String            fileName) {            try            {       Scanner sc            =            new            Scanner(new            File(fileName));            while            (sc.hasNext()) {            String            str            =            sc.nextLine();            Organization.out.println(str);       }       sc.close();     }            grab            (IOException eastward) {            // TODO Auto-generated catch block            e.printStackTrace();     }   } Output [From File] Java provides several ways to read the file.

You can utilize the hasNext() method to determine if there is any more token left to read in the file and loop until it returns false. Though you should remember that adjacent() or nextLine() may block until data is available fifty-fifty if hasNext() return truthful. This code is reading the content of "file.txt" line by line. See this tutorial to learn more almost the Scanner class and file reading in Java.

iv. Reading a text file using Stream in Java 8

The JDK eight release has brought some cool new features e.g. lambda expression and streams which make file reading even smoother in Java. Since streams are lazy, you can use them to read-only lines you want from the file e.grand. you tin can read all non-empty lines by filtering empty lines. The employ of method reference as well makes the file reading code much more elementary and concise, and then much then that y'all can read a file in just one line every bit shown beneath:

Files.lines(Paths.get("newfile.txt")).forEach(System.out:            :println);  Output This is the            commencement            line of file  something is better than nothing            this            is the            last            line of the file

At present, if you want to do some pre-processing, here is lawmaking to trim each line, filter empty lines to merely read non-empty ones, and call back, this is lazy because Files.lines() method return a stream of String and Streams are lazy in JDK 8 (run across Java 8 in Activeness).

Files.lines(new            File("newfile.txt").toPath()) .map(s            -> s.trim())  .filter(due south            ->            !south.isEmpty())  .forEach(Arrangement.out:            :println);          

We'll apply this lawmaking to read a file that contains a line that is full of whitespace and an empty line, the same one which we accept used in the previous instance, just this time, the output volition non contain 5 line but just 3 lines because empty lines are already filtered, every bit shown below:

Output This is the            first            line of file something is better than nothing            this            is the            last            line of the file

Yous can see simply three out of five lines appeared because the other ii got filtered. This is only the tip of the iceberg on what you tin do with Java SE 8, See Coffee SE viii for Really Impatient to learn more nigh Java 8 features.

Reading text file in Java 8 example

five. How to read a text file as Cord in Java

Sometimes you read the full content of a text file as String in Coffee. This is mostly the case with small text files as for large files you will face java.lang.OutOfMemoryError: java heap space fault. Prior to Java 7, this requires a lot of boiler lawmaking because you need to use a BufferedReader to read a text file line past line and and so add all those lines into a StringBuilder and finally render the String generated from that.

Now you don't need to do all that, you tin can use the Files.readAllBytes() method to read all bytes of the file in i shot. Once done that y'all can convert that byte array into String. as shown in the post-obit instance:

            public            static            String            readFileAsString(String            fileName) {            String            information            =            "";            attempt            {            data            =            new            String(Files.readAllBytes(Paths.become("file.txt")));     }            catch            (IOException e) {       e.printStackTrace();     }            return            data;   } Output [From File] Coffee provides several ways to read file

This was a rather small file and then it was pretty like shooting fish in a barrel. Though, while using readAllBytes() you should recall character encoding. If your file is not in platform'southward default graphic symbol encoding so you lot must specify the character doing explicitly both while reading and converting to String. Use the overloaded version of readAllBytes() which accepts graphic symbol encoding. Yous can also see how I read XML every bit String in Java here.

6. Reading the whole file in a List

Similar to the last case, sometimes you need all lines of the text file into an ArrayList or Vector or simply on a List. Prior to Java vii, this chore likewise involves boilerplate eastward.chiliad. reading files line by line, adding them into a listing, and finally returning the listing to the caller, but after Java 7, information technology'south very uncomplicated at present. You just need to use the Files.readAllLines() method, which returns all lines of the text file into a List, as shown below:

            public            static            List<String> readFileInList(Cord            fileName) {            List<String> lines            =            Collections.emptyList();            try            {       lines            =            Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);     }            grab            (IOException due east) {            // TODO Auto-generated catch cake            e.printStackTrace();     }            return            lines; }

Similar to the last case, you should specify grapheme encoding if it'southward unlike from than platform's default encoding. Y'all can apply see I have specified UTF-8 here. Once again, use this trick only if you know that file is small and y'all take enough retentivity to hold a List containing all lines of the text file, otherwise your Coffee program will crash with OutOfMemoryError.

10 Examples to read text file in Java


vii. How to read a text file in Coffee into an array

This example is also very similar to the concluding two examples, this time, we are reading the contents of the file into a String assortment. I have used a shortcut here, get-go, I have read all the lines as List and then converted the listing to an assortment.

This results in simple and elegant code, but y'all can likewise read data into a character array as shown in the first case. Use the read(char[] data) method while reading data into a grapheme array.

Here is an example of reading a text file into Cord array in Java:

            public            static            String[] readFileIntoArray(String            fileName) {            Listing<String>            listing            =            readFileInList(fileName);            render            listing.toArray(new            Cord[list.size()]); }

This method leverage our existing method which reads the file into a List and the lawmaking here is just to convert a list to an array in Java.

viii. How to read a file line by line in Java

This is one of the interesting examples of reading a text file in Java. You frequently need file data as line by line. Fortunately, both BufferedReader and Scanner provide convenient utility method to read line by line. If you lot are using BufferedReader then you can use readLine() and if you are using Scanner and so you lot can apply nextLine() to read file contents line by line. In our example, I take used BufferedReader as shown beneath:

            public            static            void            readFileLineByLine(String            fileName) {            try            (BufferedReader br            =            new            BufferedReader(new            FileReader(fileName))) {            Cord            line            =            br.readLine();            while            (line            !            =            naught) {            System.out.println(line);         line            =            br.readLine();       }     }            catch            (IOException e) {       due east.printStackTrace();     }   }

Just recall that A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a line feed.

How to read a file line by line in Java

Coffee Program to read a text file in Java

Here is the complete Java program to read a apparently text file in Java. You tin can run this program in Eclipse provided y'all create the files used in this program e.thousand. "sample.txt", "file.txt", and "newfile.txt". Since I am using a relative path, you must ensure that files are in the classpath. If you are running this plan in Eclipse, y'all can simply create these files in the root of the project directory. The programme will throw FileNotFoundException or NoSuchFileExcpetion if information technology is non able to find the files.

            import            java.io.BufferedReader;            import            java.io.File;            import            java.io.FileNotFoundException;            import            java.io.FileReader;            import            java.io.IOException;            import            coffee.nio.charset.StandardCharsets;            import            java.nio.file.Files;            import            coffee.nio.file.Paths;            import            java.util.Collections;            import            java.util.List;            import            java.util.Scanner;            /*  * Java Program read a text file in multiple way.  * This program demonstrate how you can use FileReader,  * BufferedReader, and Scanner to read text file,  * along with newer utility methods added in JDK 7  * and 8.   */            public            class            FileReadingDemo            {            public            static            void            main(String[] args) throws Exception {            // Example ane - reading a text file using FileReader in Coffee            readTextFileUsingFileReader("sample.txt");            // Example 2 - reading a text file in Java using BufferedReader            readTextFileUsingBufferdReader("file.txt");            // Case 3 - reading a text file in Java using Scanner            readTextFileUsingScanner("file.txt");            // Example 4 - reading a text file using Stream in Java 8            Files.lines(Paths.get("newfile.txt")).forEach(Organization.out:            :println);            // Case 5 - filtering empty lines from a file in Coffee 8            Files.lines(new            File("newfile.txt").toPath())     .map(s            -> south.trim())      .filter(south            ->            !s.isEmpty())      .forEach(Arrangement.out:            :println);            // Instance 6 - reading a text file as String in Java            readFileAsString("file.txt");            // Example 7 - reading whole file in a Listing            List<String> lines            =            readFileInList("newfile.txt");            System.out.println("Total number of lines in file: "            +            lines.size());            // Example 8 - how to read a text file in java into an array            String[] arrayOfString            =            readFileIntoArray("newFile.txt");            for(String            line:            arrayOfString){            Organization.out.println(line);     }            // Instance ix - how to read a text file in java line by line            readFileLineByLine("newFile.txt");            // Instance 10 - how to read a text file in java using eclipse            // all examples y'all tin run in Eclipse, there is cipher special nearly it.                        }            public            static            void            readTextFileUsingFileReader(String            fileName) {            try            {       FileReader textFileReader            =            new            FileReader(fileName);       char[] buffer            =            new            char[8096];            int            numberOfCharsRead            =            textFileReader.read(buffer);            while            (numberOfCharsRead            !            =            -1) {            Arrangement.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }       textFileReader.shut();     }            catch            (IOException eastward) {            // TODO Auto-generated catch cake            e.printStackTrace();     }   }            public            static            void            readTextFileUsingBufferdReader(String            fileName) {            endeavor            {       FileReader textFileReader            =            new            FileReader(fileName);       BufferedReader bufReader            =            new            BufferedReader(textFileReader);        char[] buffer            =            new            char[8096];            int            numberOfCharsRead            =            bufReader.read(buffer);            // read will exist from            // retentivity            while            (numberOfCharsRead            !            =            -1) {            Arrangement.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }        bufReader.close();      }            catch            (IOException due east) {            // TODO Auto-generated take hold of block            e.printStackTrace();     }   }            public            static            void            readTextFileUsingScanner(String            fileName) {            endeavour            {       Scanner sc            =            new            Scanner(new            File(fileName));            while            (sc.hasNext()) {            Cord            str            =            sc.nextLine();            Organization.out.println(str);       }       sc.shut();     }            take hold of            (IOException e) {            // TODO Automobile-generated grab cake            e.printStackTrace();     }   }            public            static            Cord            readFileAsString(String            fileName) {            Cord            information            =            "";            try            {            data            =            new            String(Files.readAllBytes(Paths.get("file.txt")));     }            take hold of            (IOException e) {       east.printStackTrace();     }            render            data;   }            public            static            List<String> readFileInList(Cord            fileName) {            Listing<String> lines            =            Collections.emptyList();            try            {       lines            =            Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);     }            catch            (IOException e) {            // TODO Auto-generated take hold of block            e.printStackTrace();     }            return            lines;   }            public            static            String[] readFileIntoArray(Cord            fileName) {            Listing<String>            list            =            readFileInList(fileName);            return            listing.toArray(new            Cord[list.size()]);    }            public            static            void            readFileLineByLine(String            fileName) {            try            (BufferedReader br            =            new            BufferedReader(new            FileReader(fileName))) {            String            line            =            br.readLine();            while            (line            !            =            null) {            Organization.out.println(line);         line            =            br.readLine();       }     }            catch            (IOException e) {       e.printStackTrace();     }   } }

I take not printed the output here considering nosotros have already gone through that and discuss in corresponding examples, but you need Coffee 8 to compile and run this program. If you are running on Java vii, then only remove the example 4 and five which uses Java 8 syntax and features and the program should run fine.

That's all most how to read a text file in Java. We have looked at all major utilities and classes which yous can employ to read a file in Java similarFileReader, BufferedReader, and Scanner. We have besides looked at utility methods added on Java NIO 2 on JDK 7 like. Files.readAllLines() and Files.readAllBytes() to read the file in List and Cord respectively.

Other Coffee File tutorials for beginners

  • How to check if a File is hidden in Java? (solution)
  • How to read an XML file in Java? (guide)
  • How to read an Excel file in Java? (guide)
  • How to read an XML file as String in Java? (example)
  • How to copy non-empty directories in Java? (example)
  • How to read/write from/to RandomAccessFile in Coffee? (tutorial)
  • How to append text to a File in Java? (solution)
  • How to read a Nothing file in Coffee? (tutorial)
  • How to read from a Memory Mapped file in Coffee? (case)

Finally, nosotros accept also touched new way of file reading with Java 8 Stream, which provides lazy reading and the useful pre-processing pick to filter unnecessary lines.

voigttherk1945.blogspot.com

Source: https://javarevisited.blogspot.com/2016/07/10-examples-to-read-text-file-in-java.html