Read File Into an Array in Java
Last Updated :
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 file
- Using Scanner to read the file
- readAllLines() method
- Using FileReader
1. Using BufferedReader to read the file
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.
Syntax:
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 java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class GFG {
public static void main(String[] args)
throws IOException
{
List<String> listOfStrings
= new ArrayList<String>();
BufferedReader bf = new BufferedReader(
new FileReader( "file.txt" ));
String line = bf.readLine();
while (line != null ) {
listOfStrings.add(line);
line = bf.readLine();
}
bf.close();
String[] array
= listOfStrings.toArray( new String[ 0 ]);
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.
2. Using Scanner to read the file
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 java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class GFG {
public static void main(String[] args)
throws IOException
{
List<String> listOfStrings
= new ArrayList<String>();
Scanner sc = new Scanner( new FileReader( "file.txt" ))
.useDelimiter( ",\\s*" );
String str;
while (sc.hasNext()) {
str = sc.next();
listOfStrings.add(str);
}
String[] array
= listOfStrings.toArray( new String[ 0 ]);
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
3. readAllLines() method
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 java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class Box {
public static void main(String[] args)
throws IOException
{
List<String> listOfStrings
= new ArrayList<String>();
listOfStrings
= Files.readAllLines(Paths.get( "file.txt" ));
String[] array
= listOfStrings.toArray( new String[ 0 ]);
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.
4. Using FileReader
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 java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
class GFG {
public static void main(String[] args)
throws IOException
{
List<String> listOfStrings
= new ArrayList<String>();
FileReader fr = new FileReader( "file.txt" );
String s = new String();
char ch;
while (fr.ready()) {
ch = ( char )fr.read();
if (ch == '\n' || ch == ' ' || ch == ',' ) {
listOfStrings.add(s.toString());
s = new String();
}
else {
s += ch;
}
}
if (s.length() > 0 ) {
listOfStrings.add(s.toString());
}
String[] array
= listOfStrings.toArray( new String[ 0 ]);
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.
Share your thoughts in the comments
Please Login to comment...