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.
Similar Reads
Reverse an Array in Java
Reversing an Array is a common task in every programming language. In Java, there are multiple ways to reverse an array. We can reverse it manually or by using built-in Java methods. In this article, we will discuss different methods to reverse an array with examples. Let us first see the most commo
4 min read
Array getInt() Method in Java
The java.lang.reflect.Array.getInt() is an inbuilt method in Java and is used to return an element at the given index from the specified Array as a int. Syntax Array.getInt(Object []array, int index) Parameters: This method accepts two mandatory parameters: array: The object array whose index is to
3 min read
How to Initialize an Array in Java?
An array in Java is a linear data structure, which is used to store multiple values of the same data type. In array each element has a unique index value, which makes it easy to access individual elements. We first need to declare the size of an array because the size of the array is fixed in Java.
6 min read
Initialize an ArrayList in Java
ArrayList is a part of the collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though it may be slower than standard arrays, but can be helpful in programs where lots of manipulation in the array is needed. ArrayList inherits the AbstractList class and im
4 min read
One Dimensional Array in Java
An array is a type of Data Structure that can store collections of elements. These elements are stored in contiguous memory locations and the it provides efficient access to each element based on the index of the array element. In this article, we will learn about a one-dimensional array in Java. Wh
7 min read
IntBuffer array() method in Java
The array() method of java.nio.IntBuffer Class is used to Return the int array that backs this buffer. Modifications to this buffer's content will cause the returned array's content to be modified, and vice versa. Invoke() the hasArray() method are used before invoking this method in order to ensure
3 min read
How to Return an Array in Java?
An array is a data structure that consists of a group of elements of the same data type such that each element of the array can be identified by a single array index or key. The elements of the array are stored in a way that the address of any of the elements can be calculated using the location of
5 min read
IntBuffer arrayOffset() method in Java
The arrayOffset() method of java.nio.IntBuffer class is used to return the offset within the buffer's backing array of the first element of the buffer. It means that if this buffer is backed by an array, then buffer position p corresponds to array index p + arrayOffset(). Inorder to check whether th
3 min read
Array get() Method in Java
The java.lang.reflect.Array.get() is an inbuilt method in Java and is used to return the element at a given index from the specified Array. Syntax Array.get(Object []array, int index) Parameters : This method accepts two mandatory parameters: array: The object array whose index is to be returned. in
3 min read
Array getLong() Method in Java
The java.lang.reflect.Array.getLong() is an inbuilt method in Java and is used to return an element at the given index from a specified Array as a long. Syntax: Array.getLong(Object []array, int index) Parameters : This method accepts two mandatory parameters: array: The object array whose index is
3 min read