Java Program to Read File From Location

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 exist using a Reader implementations to read it. There are several ways to read a patently text file in Java east.yard. y'all tin employ FileReader, BufferedReader or Scanner to read a text file. Every utility provides something special e.one thousand. BufferedReader provides buffering of information for fast reading, and Scanner provides parsing ability.

You can also employ both BufferedReader and Scanner to read a text file line by line in Java. Then Java SE 8 introduces some other Stream form coffee.util.stream.Stream which provides a lazy and more efficient way to read a file.

The JDK 7 besides introduces a couple of prissy utility e.g. Files class and try-with-resource construct which made reading a text file, even more than, 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 detail to choose the right tool for the chore depending on the size of file, the content of the file, and how you desire to read.

one. Reading a text file using FileReader

The FileReader is your general-purpose Reader implementation to read a file. Information technology accepts a String path to file or a coffee.io.File instance to start 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(String            fileName) {            try            {       FileReader textFileReader            =            new            FileReader(fileName);       char[] buffer            =            new            char[8096];            int            numberOfCharsRead            =            textFileReader.read(buffer);            while            (numberOfCharsRead            !            =            -1) {            Organization.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }       textFileReader.shut();     }            catch            (IOException due east) {            // TODO Motorcar-generated take hold of block            e.printStackTrace();     }   }  Output Once upon a            time, we wrote a plan to read            data            from a            text            file. The plan failed to read a large file but and then Coffee 8 come to rescue, which made reading file lazily using Streams.          

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

I am using an 8KB of the buffer, and then in one call I am limited to read that much data merely. You tin have a bigger or smaller buffer depending upon your heap memory and file size. You lot should also find that I am looping until read(char[]) returns -1 which signals the stop of the file.

Another interesting thing to note is to call to String.valueOf(buffer, 0, numberOfCharsRead), which is required considering y'all might not have 8KB of data in the file or fifty-fifty with a bigger file, the last telephone call may not exist able to fill the char array and it could contain muddied data from the last read.

2. Reading a text file in Coffee using BufferedReader

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

The default size of the internal buffer is 8KB which is skilful enough for most purpose, but y'all can as well increase or decrease buffer size while creating BufferedReader object. The reading code is like 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            // memory            while            (numberOfCharsRead            !            =            -one) {            Organisation.out.println(Cord.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }        bufReader.close();      }            catch            (IOException e) {            // TODO Automobile-generated take hold of block            e.printStackTrace();     }   }  Output [From File] Java provides several means to read file

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

In society to read the full-text file, you lot loop until read(char[]) method returns -1, which signals the cease of the file. Encounter Core Java Volume one - Fundamentals to learn more than about how BufferedReader form works in Java.

How to read a text file in Java

iii. Reading a text file in Coffee using Scanner

The third tool or class to read a text file in Java 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 i.1 versions. The Scanner is a much more than feature-rich and versatile class.

It does not just provide reading but the parsing of data also. Y'all can non only read text data but you tin too read the text as a number or float using nextInt() and nextFloat() methods.

The class uses regular expression pattern to determine token, which could be catchy for newcomers. The ii chief method to read text data from Scanner is side by side() and nextLine(), onetime i read words separated by space while after one tin be used to read a text file line by line in Java. In most cases, you lot would employ the nextLine() method every bit shown beneath:

            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 Automobile-generated catch block            due east.printStackTrace();     }   } Output [From File] Coffee provides several ways to read the file.

You tin use the hasNext() method to determine if there is any more token left to read in the file and loop until it returns faux. Though you should call up that next() or nextLine() may cake until data is available even if hasNext() return true. This code is reading the content of "file.txt" line by line. Run across this tutorial to learn more most the Scanner class and file reading in Java.

four. Reading a text file using Stream in Coffee eight

The JDK 8 release has brought some cool new features e.g. lambda expression and streams which make file reading fifty-fifty smoother in Coffee. Since streams are lazy, yous can use them to read-simply lines you want from the file due east.g. you lot can read all not-empty lines by filtering empty lines. The apply of method reference also makes the file reading code much more than simple and concise, so much so that you tin read a file in just i line as shown below:

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

Now, if you want to do some pre-processing, hither is lawmaking to trim each line, filter empty lines to but read not-empty ones, and remember, this is lazy because Files.lines() method return a stream of String and Streams are lazy in JDK 8 (run into Java 8 in Action).

Files.lines(new            File("newfile.txt").toPath()) .map(s            -> s.trim())  .filter(s            ->            !s.isEmpty())  .forEach(Organisation.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 1 which we accept used in the previous example, only this time, the output volition not incorporate 5 line simply just 3 lines because empty lines are already filtered, as shown below:

Output This is the            first            line of file something is amend than aught            this            is the            concluding            line of the file

You tin run across only three out of 5 lines appeared because the other 2 got filtered. This is just the tip of the iceberg on what y'all can do with Java SE eight, Encounter Coffee SE viii for Really Impatient to acquire more nigh Java 8 features.

Reading text file in Java 8 example

5. How to read a text file as String in Coffee

Sometimes you read the full content of a text file as String in Java. This is more often than not the case with pocket-sized text files as for large files you volition confront java.lang.OutOfMemoryError: coffee heap space error. Prior to Java 7, this requires a lot of boiler lawmaking because you need to utilise 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 demand to do all that, you can use the Files.readAllBytes() method to read all bytes of the file in ane shot. In one case done that you lot tin convert that byte array into String. as shown in the following example:

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

This was a rather pocket-sized file so information technology was pretty piece of cake. Though, while using readAllBytes() you lot should remember character encoding. If your file is not in platform's default character encoding then yous must specify the character doing explicitly both while reading and converting to String. Use the overloaded version of readAllBytes() which accepts character encoding. You can also see how I read XML equally String in Java here.

6. Reading the whole file in a List

Similar to the last example, sometimes you demand all lines of the text file into an ArrayList or Vector or simply on a List. Prior to Java 7, this task likewise involves average e.grand. reading files line past line, adding them into a list, and finally returning the list to the caller, just afterwards Java 7, it'south very simple now. You simply need to use the Files.readAllLines() method, which returns all lines of the text file into a Listing, as shown below:

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

Like to the last case, you should specify character encoding if it's different from than platform'southward default encoding. You can employ run across I accept specified UTF-8 here. Again, use this trick only if yous know that file is minor and you have enough retention to agree a List containing all lines of the text file, otherwise your Coffee plan will crash with OutOfMemoryError.

10 Examples to read text file in Java


vii. How to read a text file in Java into an assortment

This case is also very similar to the final ii examples, this fourth dimension, nosotros are reading the contents of the file into a String array. I take used a shortcut here, first, I have read all the lines as List then converted the list to an array.

This results in simple and elegant code, only you can besides read information into a character array every bit shown in the first example. Utilise the read(char[] data) method while reading data into a character array.

Hither is an example of reading a text file into String assortment in Java:

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

This method leverage our existing method which reads the file into a List and the code hither is only to convert a listing to an array in Java.

8. 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 often need file data every bit line by line. Fortunately, both BufferedReader and Scanner provide user-friendly utility method to read line by line. If you are using BufferedReader and then you can use readLine() and if you are using Scanner then you lot can use nextLine() to read file contents line by line. In our example, I have used BufferedReader equally shown beneath:

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

Just retrieve that A line is considered to exist terminated by any one of a line feed ('\northward'), a carriage return ('\r'), or a wagon return followed immediately by a line feed.

How to read a file line by line in Java

Java Program to read a text file in Java

Hither is the consummate Coffee program to read a apparently text file in Java. Y'all tin run this plan in Eclipse provided you create the files used in this plan eastward.g. "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 programme in Eclipse, yous tin just create these files in the root of the project directory. The program will throw FileNotFoundException or NoSuchFileExcpetion if it is not able to find the files.

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

I take not printed the output here considering we have already gone through that and discuss in respective examples, but yous demand Java eight to compile and run this program. If you lot are running on Java vii, then just remove the example 4 and 5 which uses Java 8 syntax and features and the programme should run fine.

That's all about how to read a text file in Coffee. We take looked at all major utilities and classes which yous tin can employ to read a file in Java likeFileReader, BufferedReader, and Scanner. We have also looked at utility methods added on Coffee NIO 2 on JDK 7 similar. Files.readAllLines() and Files.readAllBytes() to read the file in List and String respectively.

Other Java File tutorials for beginners

  • How to check if a File is hidden in Java? (solution)
  • How to read an XML file in Coffee? (guide)
  • How to read an Excel file in Coffee? (guide)
  • How to read an XML file every bit Cord in Java? (case)
  • How to copy not-empty directories in Java? (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 Coffee? (case)

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

tafollawaisenly.blogspot.com

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

Related Posts

0 Response to "Java Program to Read File From Location"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel