Read File Into an Array in Java - GeeksforGeeks

21 Feb, 2022
In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method. To store the content of the file better use the collection storage type instead of a static array as we don’t know the exact lines or word count of files. Then convert the collection type to the array as per the requirement.
As to read the content of the file, first we need to create a file with some text in it. Let us consider the below text is present in the file named file.txt
Geeks,for
Geeks
Learning portal
There are mainly 4 approaches to read the content of the file and store it in the array. They are mentioned below-
Using BufferedReader to read the fileUsing Scanner to read the filereadAllLines() methodUsing FileReader
Using BufferedReader to read the file
Using Scanner to read the file
readAllLines() method
Using FileReader
It was the easiest way for developers to code it to get the content of the file and it is also a preferred way to read the file because it takes fewer number reading calls because it uses a char buffer that simultaneously reads multiple values from a character input stream.
BufferedReader bf=new BufferedReader (new FileReader(filename))
BufferedReader also provides a method called readLine that takes the entire line in a file as a string.
Below is the example code to store the content of the file in an array.
Example:
Java
// import necessary packagesimport java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.List; public class GFG {    // to handle exceptions include throws    public static void main(String[] args)        throws IOException    {        // list that holds strings of a file        List<String> listOfStrings            = new ArrayList<String>();               // load data from file        BufferedReader bf = new BufferedReader(            new FileReader("file.txt"));               // read entire line as string        String line = bf.readLine();               // checking for end of file        while (line != null) {            listOfStrings.add(line);            line = bf.readLine();        }               // closing bufferreader object        bf.close();               // storing the data in arraylist to array        String[] array            = listOfStrings.toArray(new String[0]);               // printing each line of file        // which is stored in array        for (String str : array) {            System.out.println(str);        }    }}
Output:
Geeks,for
Geeks
Learning portal
Explanation: In this code, we used BufferedReader to read and load the content of a file, and then we used the readLine method to get each line of the file as a string and stored/added in ArrayList and finally we converted that ArrayList to Array using toArray method.
But in order to specify any delimiter to separate data in a file, In that case, a Scanner will be helpful. As we can see that there are 2 strings in the first line of a file but using BufferedReader we got them as a combined string.
Note: While reading the file, if the file is in same location where the program code is saved then no need to mention path just specify the file name. If the file is in a different location with respect to the program saved location then we should specify the path along with the filename.
The scanner is mainly used to read data from users for primitive datatypes. But even to get data from a file Scanner can be used along with File or FileReader to load data of a file. This Scanner generally breaks the tokens into strings by a default delimiter space but even we can explicitly specify the other delimiters by using the useDelimiter method.
Syntax:
Scanner sc = new Scanner(new FileReader("filename")).useDelimiter("delimiter to separate strings");
The scanner is present in util package which we need to import before using it and it also provides readLine() and hasNext() to check the end of the file i.e., whether there are any strings available or not to read.
Below is the example code to store the content of the file in an array using Scanner.
Example:
Java
// import necessary packagesimport java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.Scanner; public class GFG {    // include throws to handle some file handling exceptions    public static void main(String[] args)        throws IOException    {        // arraylist to store strings        List<String> listOfStrings            = new ArrayList<String>();               // load content of file based on specific delimiter        Scanner sc = new Scanner(new FileReader("file.txt"))                         .useDelimiter(",\\s*");        String str;               // checking end of file        while (sc.hasNext()) {            str = sc.next();                       // adding each string to arraylist            listOfStrings.add(str);        }               // convert any arraylist to array        String[] array            = listOfStrings.toArray(new String[0]);               // print each string in array        for (String eachString : array) {            System.out.println(eachString);        }    }}
 Output
Geeks
for
Geeks
Learning portal
Explanation: In this code, we used Scanner to read and load the content of the file, and here there is a flexibility of specifying the delimiter using the useDelimiter method so that we can separate strings based on delimiter and each of these strings separated based on delimiter are stored/added in ArrayList and we can check EOF by using hasNext method. Finally, we converted that ArrayList to Array using the toArray method.
As we specified delimiter value as “,” (comma) we got 2 separated strings geeks and for. If we didn’t specify any delimiter method to Scanner then it will separate strings based on spaces.
Note: There is another method called readAllLines present in Files class use to read the content of file line by line
To use this first we need to import Files and Paths classes from the file package. The benefit of using this method is it reduces the lines of code to fetch and store data. Syntax of this is mentioned below-
FIles.readAllLines(Paths("filename"))
Below is the code to load the content of the file and store it in an array using readAllLines method.
Example:
Java
// import necessary packages and classesimport java.io.IOException;import java.nio.file.Files;import java.nio.file.Paths;import java.util.ArrayList;import java.util.List; public class Box {    // add throws to main method to handle exceptions    public static void main(String[] args)        throws IOException    {        List<String> listOfStrings            = new ArrayList<String>();               // load the data from file        listOfStrings            = Files.readAllLines(Paths.get("file.txt"));               // convert arraylist to array        String[] array            = listOfStrings.toArray(new String[0]);               // print each line of string in array        for (String eachString : array) {            System.out.println(eachString);        }    }}
Output
Geeks,for
Geeks
Learning portal
Explanation: Here we used readAllLines method to get each line in a file and return a list of strings. This list is converted to an array using the toArray method. 
Using FileReader we can load the data in the file and can read character-wise data from the FileReader object. Before using FIleReader in a program we need to import FileReader class from the io package.
Syntax:
FileReader filereaderObj=new FileReader("filename");
Let’s see the below example code to read data from a file and store it in an array using FileReader.
Example:
Java
// import necessary packagesimport java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.List; class GFG {    // to handle exceptions include throws    public static void main(String[] args)        throws IOException    {        // list that holds strings of a file        List<String> listOfStrings            = new ArrayList<String>();               // load data from file        FileReader fr = new FileReader("file.txt");               // Created a string to store each character        // to form word        String s = new String();        char ch;               // checking for EOF        while (fr.ready()) {            ch = (char)fr.read();                           // Used to specify the delimiters            if (ch == '\n' || ch == ' ' || ch == ',') {                               // Storing each string in arraylist                listOfStrings.add(s.toString());                               // clearing content in string                s = new String();            }            else {                // appending each character to string if the                // current character is not delimiter                s += ch;            }        }        if (s.length() > 0) {                       // appending last line of strings to list            listOfStrings.add(s.toString());        }        // storing the data in arraylist to array        String[] array            = listOfStrings.toArray(new String[0]);               // printing each line of file which is stored in        // array        for (String str : array) {            System.out.println(str);        }    }}
 Output
Geeks
for
Geeks
Learning
portal
Explanation: In this code, we used FileReader to load data from a file in its object. This object holds data as a stream of characters and we can fetch data from it as a character by character. So we store each character in a string and if the character fetched was any delimiter i.e., specified in if statement [\n, (space) ‘ ‘, (comma) ‘,’] then we store that string in ArrayList and clear the content in the string if not then append that character to string. Like this, we store all the strings in a file into an ArrayList and this is converted to Array.
These are all possible approaches that can be followed to read data from files and store it in the array.
 
sagartomar9927
kk773572498
as5853535
Java-Arrays
Java-Files
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Internal Working of HashMap in Java
Comparator Interface in Java with Examples
Strings in Java