Java Eclips Code Read From Text File Sample Code

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 grapheme data. Since a text file is total of characters, you should be using a Reader implementations to read it. There are several means to read a plain text file in Coffee e.grand. yous tin can use 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 ability.

You can too use both BufferedReader and Scanner to read a text file line by line in Java. Then Java SE eight introduces another Stream class java.util.stream.Stream which provides a lazy and more than efficient way to read a file.

The JDK vii also introduces a couple of overnice utility e.one thousand. Files grade 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 Java with their pros, cons, and important points about each approach. This will give you enough item to choose the correct tool for the chore depending on the size of file, the content of the file, and how you desire to read.

ane. Reading a text file using FileReader

The FileReader is your general-purpose Reader implementation to read a file. It accepts a Cord path to file or a coffee.io.File instance to starting time reading. It also provides a couple of overloaded read() methods to read a character or read characters into an array or into a CharBuffer object.

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

            public            static            void            readTextFileUsingFileReader(Cord            fileName) {            try            {       FileReader textFileReader            =            new            FileReader(fileName);       char[] buffer            =            new            char[8096];            int            numberOfCharsRead            =            textFileReader.read(buffer);            while            (numberOfCharsRead            !            =            -1) {            Organisation.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }       textFileReader.close();     }            take hold of            (IOException e) {            // TODO Auto-generated catch cake            east.printStackTrace();     }   }  Output One time upon a            time, we wrote a programme to read            data            from a            text            file. The program failed to read a big file just then Java eight come to rescue, which made reading file lazily using Streams.          

You can see that instead of reading one character at a time, I am reading characters into an array. This is more efficient considering read() will access the file several times but read(char[]) will access the file just i fourth dimension to read the same corporeality of data.

I am using an 8KB of the buffer, and so in ane phone call I am limited to read that much data but. Y'all can have a bigger or smaller buffer depending upon your heap retentiveness and file size. You should likewise find that I am looping until read(char[]) returns -ane which signals the finish of the file.

Another interesting affair to note is to call to String.valueOf(buffer, 0, numberOfCharsRead), which is required because you lot might not have 8KB of data in the file or even with a bigger file, the final telephone call may non exist able to fill the char array and it could incorporate dirty data from the last read.

2. Reading a text file in Java using BufferedReader

The BufferedReader class is a Decorator which provides buffering functionality to FileReader or any other Reader. This class buffer input from source due east.g. files into memory for the efficient read. In the example of BufferedReader, the telephone call to read() doesn't always goes to file if it can observe the data in the internal buffer of BufferedReader.

The default size of the internal buffer is 8KB which is adept enough for most purpose, but you lot can also increase or subtract buffer size while creating BufferedReader object. The reading code is similar to the previous instance.

            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 be from            // memory            while            (numberOfCharsRead            !            =            -1) {            System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }        bufReader.close();      }            take hold of            (IOException e) {            // TODO Automobile-generated catch block            due east.printStackTrace();     }   }  Output [From File] Coffee provides several ways to read file

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

In order to read the full-text file, yous loop until read(char[]) method returns -1, which signals the stop of the file. Come across Core Java Volume 1 - Fundamentals to acquire more about how BufferedReader class works in Java.

How to read a text file in Java

3. Reading a text file in Java using Scanner

The third tool or form to read a text file in Java is the Scanner, which was added on JDK 1.five release. The other two FileReader and BufferedReader are present from JDK ane.0 and JDK 1.1 versions. The Scanner is a much more feature-rich and versatile class.

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

The class uses regular expression pattern to determine token, which could be tricky for newcomers. The two main method to read text data from Scanner is next() and nextLine(), former one read words separated by space while later one can be used to read a text file line by line in Java. In most cases, y'all would use the nextLine() method every bit shown below:

            public            static            void            readTextFileUsingScanner(String            fileName) {            endeavour            {       Scanner sc            =            new            Scanner(new            File(fileName));            while            (sc.hasNext()) {            String            str            =            sc.nextLine();            System.out.println(str);       }       sc.close();     }            take hold of            (IOException e) {            // TODO Auto-generated take hold of block            east.printStackTrace();     }   } Output [From File] Java provides several means to read the file.

Y'all can use the hasNext() method to determine if there is any more than token left to read in the file and loop until information technology returns false. Though y'all should remember that side by side() or nextLine() may cake until data is bachelor even if hasNext() return true. This code is reading the content of "file.txt" line by line. See this tutorial to learn more about the Scanner class and file reading in Coffee.

4. Reading a text file using Stream in Java 8

The JDK 8 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 lot can employ them to read-but lines y'all want from the file e.g. y'all can read all non-empty lines past filtering empty lines. The utilise of method reference too makes the file reading code much more uncomplicated and concise, so much so that you can read a file in just one line as shown beneath:

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

Now, if y'all desire to practice some pre-processing, here is code to trim each line, filter empty lines to only read non-empty ones, and remember, this is lazy considering Files.lines() method return a stream of Cord and Streams are lazy in JDK viii (see Java 8 in Action).

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

We'll use this code to read a file that contains a line that is full of whitespace and an empty line, the same one which nosotros accept used in the previous example, but this time, the output will not contain five line just just three lines because empty lines are already filtered, as shown below:

Output This is the            get-go            line of file something is better than naught            this            is the            concluding            line of the file

You lot tin run into only three out of v lines appeared because the other two got filtered. This is just the tip of the iceberg on what y'all can do with Java SE 8, See Java SE viii for Really Impatient to learn more virtually Java 8 features.

Reading text file in Java 8 example

v. How to read a text file as String in Java

Sometimes you read the full content of a text file as String in Java. This is mostly the case with small text files as for large files y'all will confront java.lang.OutOfMemoryError: java heap space error. Prior to Coffee vii, this requires a lot of banality code considering you lot need to use a BufferedReader to read a text file line past line and then add all those lines into a StringBuilder and finally return the String generated from that.

Now yous don't need to exercise all that, you can use the Files.readAllBytes() method to read all bytes of the file in ane shot. Once washed that you can catechumen that byte array into String. as shown in the following case:

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

This was a rather small file so it was pretty like shooting fish in a barrel. Though, while using readAllBytes() you should retrieve character encoding. If your file is not in platform's default character encoding and so you must specify the character doing explicitly both while reading and converting to Cord. Use the overloaded version of readAllBytes() which accepts character encoding. You can too meet how I read XML as String in Coffee here.

vi. Reading the whole file in a List

Similar to the final example, sometimes you lot need all lines of the text file into an ArrayList or Vector or simply on a List. Prior to Java seven, this task also involves average east.g. reading files line by line, adding them into a list, and finally returning the listing to the caller, but after Java 7, information technology'due south very simple now. You only need to use the Files.readAllLines() method, which returns all lines of the text file into a List, as shown beneath:

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

Similar to the last example, you should specify character encoding if it's dissimilar from than platform's default encoding. You lot tin employ come across I have specified UTF-eight here. Again, utilise this pull a fast one on only if you know that file is small and yous accept enough retentivity to concord 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


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

This example is also very similar to the concluding 2 examples, this time, we are reading the contents of the file into a String array. I have used a shortcut here, first, I have read all the lines every bit List then converted the listing to an array.

This results in simple and elegant code, but you can too read data into a character assortment equally shown in the outset example. Use the read(char[] information) method while reading data into a graphic symbol array.

Here is an example of reading a text file into String array in Coffee:

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

This method leverage our existing method which reads the file into a Listing and the code here is simply to convert a list to an array in Coffee.

8. How to read a file line past line in Java

This is i of the interesting examples of reading a text file in Java. Yous often demand file data as line past line. Fortunately, both BufferedReader and Scanner provide convenient utility method to read line past line. If you are using BufferedReader then you can use readLine() and if y'all are using Scanner so yous can employ nextLine() to read file contents line by line. In our example, I have used BufferedReader equally shown below:

            public            static            void            readFileLineByLine(String            fileName) {            effort            (BufferedReader br            =            new            BufferedReader(new            FileReader(fileName))) {            String            line            =            br.readLine();            while            (line            !            =            null) {            System.out.println(line);         line            =            br.readLine();       }     }            take hold of            (IOException eastward) {       e.printStackTrace();     }   }

Simply recollect that A line is considered to exist terminated by any one of a line feed ('\northward'), a wagon return ('\r'), or a railroad vehicle return followed immediately past a line feed.

How to read a file line by line in Java

Java Program to read a text file in Java

Here is the complete Java program to read a plain text file in Java. You tin run this program in Eclipse provided you create the files used in this program eastward.g. "sample.txt", "file.txt", and "newfile.txt". Since I am using a relative path, you lot must ensure that files are in the classpath. If you are running this plan in Eclipse, yous tin can but create these files in the root of the projection directory. The program will throw FileNotFoundException or NoSuchFileExcpetion if information technology is not able to find the files.

            import            java.io.BufferedReader;            import            coffee.io.File;            import            coffee.io.FileNotFoundException;            import            coffee.io.FileReader;            import            coffee.io.IOException;            import            java.nio.charset.StandardCharsets;            import            java.nio.file.Files;            import            coffee.nio.file.Paths;            import            java.util.Collections;            import            coffee.util.List;            import            java.util.Scanner;            /*  * Coffee Programme read a text file in multiple way.  * This plan demonstrate how you tin use FileReader,  * BufferedReader, and Scanner to read text file,  * along with newer utility methods added in JDK seven  * and 8.   */            public            class            FileReadingDemo            {            public            static            void            main(String[] args) throws Exception {            // Instance 1 - reading a text file using FileReader in Java            readTextFileUsingFileReader("sample.txt");            // Case 2 - reading a text file in Java using BufferedReader            readTextFileUsingBufferdReader("file.txt");            // Example 3 - reading a text file in Java using Scanner            readTextFileUsingScanner("file.txt");            // Case 4 - reading a text file using Stream in Java 8            Files.lines(Paths.get("newfile.txt")).forEach(System.out:            :println);            // Example 5 - filtering empty lines from a file in Java viii            Files.lines(new            File("newfile.txt").toPath())     .map(s            -> southward.trim())      .filter(s            ->            !due south.isEmpty())      .forEach(System.out:            :println);            // Example 6 - reading a text file as Cord in Coffee            readFileAsString("file.txt");            // Case 7 - reading whole file in a Listing            List<String> lines            =            readFileInList("newfile.txt");            System.out.println("Total number of lines in file: "            +            lines.size());            // Case 8 - how to read a text file in java into an array            String[] arrayOfString            =            readFileIntoArray("newFile.txt");            for(Cord            line:            arrayOfString){            Organisation.out.println(line);     }            // Case 9 - how to read a text file in java line by line            readFileLineByLine("newFile.txt");            // Case 10 - how to read a text file in java using eclipse            // all examples you tin run in Eclipse, in that location is nil special about 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            !            =            -one) {            System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }       textFileReader.shut();     }            catch            (IOException eastward) {            // TODO Auto-generated catch block            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 volition be from            // retention            while            (numberOfCharsRead            !            =            -i) {            Organisation.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }        bufReader.close();      }            catch            (IOException due east) {            // TODO Automobile-generated catch block            e.printStackTrace();     }   }            public            static            void            readTextFileUsingScanner(String            fileName) {            try            {       Scanner sc            =            new            Scanner(new            File(fileName));            while            (sc.hasNext()) {            String            str            =            sc.nextLine();            System.out.println(str);       }       sc.close();     }            catch            (IOException e) {            // TODO Auto-generated catch cake            e.printStackTrace();     }   }            public            static            String            readFileAsString(Cord            fileName) {            Cord            data            =            "";            attempt            {            information            =            new            String(Files.readAllBytes(Paths.become("file.txt")));     }            take hold of            (IOException e) {       e.printStackTrace();     }            render            data;   }            public            static            List<String> readFileInList(Cord            fileName) {            List<String> lines            =            Collections.emptyList();            try            {       lines            =            Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);     }            take hold of            (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();     }            return            lines;   }            public            static            String[] readFileIntoArray(Cord            fileName) {            Listing<String>            list            =            readFileInList(fileName);            return            list.toArray(new            String[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 have not printed the output hither considering we take already gone through that and talk over in respective examples, just y'all demand Java viii to compile and run this program. If you are running on Java 7, then just remove the example iv and 5 which uses Java 8 syntax and features and the program should run fine.

That'southward all about how to read a text file in Coffee. We have looked at all major utilities and classes which you can use to read a file in Java likeFileReader, BufferedReader, and Scanner. We have also looked at utility methods added on Java NIO two on JDK 7 like. Files.readAllLines() and Files.readAllBytes() to read the file in List and Cord respectively.

Other Java File tutorials for beginners

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

Finally, we have likewise touched new way of file reading with Java 8 Stream, which provides lazy reading and the useful pre-processing option to filter unnecessary lines.

mcgregorexperwas.blogspot.com

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

0 Response to "Java Eclips Code Read From Text File Sample Code"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel