Skip to content Skip to sidebar Skip to footer

Open a File and Read Contents Into an Array Java

Prior to Java 7, reading a text file into an ArrayList involves a lot of boilerplate coding, every bit y'all demand to read the file line past line and insert each line into an ArrayList, merely from Coffee seven onward, you can use the utility method Files.readAllLines() to read all lines of a text file into a Listing. This method returns a Listing of String that contains all lines of files. After you lot can convert this List to ArrayList, LinkedList, or whatever list you want to. Btw, this the quaternary article in the serial of reading a text file in Java.

In the earlier parts, you have learned how to read a file using Scanner and BufferedReader (1). Then, reading the whole file as String (2) and finally reading a text file into an array (3 ). This programme is not very unlike from those in terms of fundamentals.

We are nevertheless going to use theread() method for Java half dozen solution and will read all text until this method returns -1 which signals the end of the file.

Reading text file into ArrayList in Coffee - BufferedReader Example

If you know how to read a file line by line, either by using Scanner or by using BufferedReader so reading a text file into ArrayList is non difficult for you. All you demand to do is read each line and store that into ArrayList, as shown in the following example:

            BufferedReader bufReader            =            new            BufferedReader(new            FileReader("file.txt"));     ArrayList<String> listOfLines            =            new            ArrayList<>();            Cord            line            =            bufReader.readLine();            while            (line            !            =            null) {       listOfLines.add(line);       line            =            bufReader.readLine();     }      bufReader.close();

Just call back to close the BufferedReader once you are washed to prevent resource leak, as you don't have a effort-with-resource statement in Java vi.

Reading text file into Listing in Coffee - Files.readAllLines Example

In Java 7, you lot don't need to write code to read and store into ArrayList, only call the Files.readAllLines() method and this volition return you a list of String, where each element is the corresponding line from the line. Since List is an ordered drove the order of lines in a file is preserved in the listing. You can later convert this Listing to ArrayList or whatsoever other implementation.

here is sample lawmaking to read text file into List in JDK 7:

            public            static            List<Cord> readFileIntoList(Cord            file) {            List<String> lines            =            Collections.emptyList();            try            {       lines            =            Files.readAllLines(Paths.get(file), StandardCharsets.UTF_8);     }            grab            (IOException e) {            // TODO Machine-generated catch cake            eastward.printStackTrace();     }            return            lines;   }

The readAllLines() method accepts a CharSet, you tin can employ a pre-defined grapheme set e.thousand. StandardCharsets.UTF_8 or StandardCharsets.UTF_16.  Y'all can as well meet these costless Java Courses to learn more about new file utility classes introduced in Java vii and viii.

Coffee Plan to read text file into ArrayList

Here is the complete Coffee programme to demonstrate both methods to read a text file into ArrayList. This program start teaches yous how to practice this in JDK 7 or Java eight using theFiles.readAllLines() method and subsequently using BufferedReader and ArrayList in Java half-dozen and lower version.

You tin can compile and run this program from the control prompt or if you want to run in Eclipse, just copy and paste in Eclipse Coffee project. The Eclipse IDE will automatically create a source file for you.

Then just right-click and Run as Java Programme. Make certain you lot take file.txt in your classpath. Since I have given the relative path here, make sure you put that file inside the Eclipse project directory.

How to read text file into List in Java - example

Reading text file into ArrayList in Coffee

            import            coffee.io.BufferedReader;            import            java.io.FileReader;            import            java.io.IOException;            import            java.nio.charset.StandardCharsets;            import            java.nio.file.Files;            import            java.nio.file.Paths;            import            coffee.util.ArrayList;            import            java.util.Collections;            import            coffee.util.List;            /*  * Coffee Program read a text file into ArrayList in Coffee vi  * and Java viii.   */            public            class            ReadFileIntoArrayList            {            public            static            void            main(Cord[] args) throws Exception {            // reading text file into List in Java 7            List<Cord> lines            =            Collections.emptyList();            try            {       lines            =            Files.readAllLines(Paths.go("file.txt"), StandardCharsets.UTF_8);     }            take hold of            (IOException due east) {            // TODO Motorcar-generated catch block            east.printStackTrace();     }            System.out.println("Content of List:");            System.out.println(lines);            // reading text file into ArrayList in Java vi            BufferedReader bufReader            =            new            BufferedReader(new            FileReader("file.txt"));     ArrayList<String> listOfLines            =            new            ArrayList<>();            String            line            =            bufReader.readLine();            while            (line            !            =            null) {       listOfLines.add(line);       line            =            bufReader.readLine();     }      bufReader.close();            System.out.println("Content of ArrayLiList:");            Arrangement.out.println(listOfLines);    }  }   Output Content of            List            :            [Python, Ruby, JavaScript] Content of ArrayLiList:            [Python, Blood-red, JavaScript]

That's all about how to read a text file into ArrayList in Java. You can see information technology'southward very like shooting fish in a barrel in Coffee 7 and Java 8 by using Files.readAllLines() method. Though you should be mindful of character encoding while reading a text file in Coffee.

 In Coffee 6 also, the solution using BufferedReader or Scanner is not very difficult to implement, simply the thing y'all demand to remember is that you are loading the whole file into retentiveness.

If the file is too big and you don't accept plenty retentiveness, your programme will die by throwing java.lang.OutOfMemoryError: Java Heap Space. In brusque, this solution is only good for a small-scale files, for the large files you should always read by streaming.

taoworkly.blogspot.com

Source: https://www.java67.com/2016/07/how-to-read-text-file-into-arraylist-in-java.html

Post a Comment for "Open a File and Read Contents Into an Array Java"