How to Read Integers From a File in Java
- Method 1: Using BufferedReader
- Method 2: Using Scanner
- Method 3: Using FileInputStream and DataInputStream
- Conclusion
- FAQ

Reading integers from a file in Java is a common task that many developers encounter. Whether you’re processing data for analysis, configuring settings, or simply managing user input, knowing how to effectively read integers from files is crucial.
In this tutorial, we will explore various methods to read integers from a file in Java, providing clear examples and detailed explanations for each approach. By the end of this guide, you will have a solid understanding of how to handle file input in Java, making your coding experience smoother and more efficient.
Method 1: Using BufferedReader
The first method we’ll explore involves using the BufferedReader
class, which is a part of the Java I/O package. This approach is efficient for reading text from a file line by line. Here’s how you can implement it:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadIntegers {
public static void main(String[] args) {
String filePath = "numbers.txt";
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
int number = Integer.parseInt(line);
System.out.println(number);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
10
20
30
In this code snippet, we start by importing the necessary classes. We specify the path of the file from which we want to read integers. The BufferedReader
reads the file line by line, and for each line, we parse the string into an integer using Integer.parseInt()
. This method is efficient for files with a manageable size and works well for text files containing one integer per line. The try-with-resources statement ensures that the BufferedReader
is closed automatically, preventing resource leaks.
Method 2: Using Scanner
Another popular method for reading integers from a file in Java is by using the Scanner
class. This approach provides a more flexible way to parse different types of data, including integers. Here’s how to implement this method:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadIntegersWithScanner {
public static void main(String[] args) {
String filePath = "numbers.txt";
try {
Scanner scanner = new Scanner(new File(filePath));
while (scanner.hasNextInt()) {
int number = scanner.nextInt();
System.out.println(number);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Output:
10
20
30
In this example, we utilize the Scanner
class to read integers from the specified file. The hasNextInt()
method checks if there are more integers to read, while nextInt()
retrieves the next integer. This method is particularly useful when the file contains mixed data types or when you want to read integers in a more controlled manner. Remember to close the Scanner
object to free up resources.
Method 3: Using FileInputStream and DataInputStream
For a more low-level approach, you can use FileInputStream
combined with DataInputStream
. This method is less common for reading text files but can be useful when dealing with binary files. Here’s how you can implement it:
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadIntegersWithDataInputStream {
public static void main(String[] args) {
String filePath = "numbers.dat";
try (DataInputStream dis = new DataInputStream(new FileInputStream(filePath))) {
while (dis.available() > 0) {
int number = dis.readInt();
System.out.println(number);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
10
20
30
In this method, we read integers from a binary file using DataInputStream
. The available()
method checks if there are more bytes to read, and readInt()
retrieves the next integer. This approach is efficient for binary files but requires that the file is formatted correctly. Using DataInputStream
is advantageous when dealing with large amounts of data or when performance is a concern.
Conclusion
In this tutorial, we’ve explored three effective methods for reading integers from a file in Java: using BufferedReader
, Scanner
, and FileInputStream
with DataInputStream
. Each method has its strengths and is suited for different scenarios, whether you’re dealing with text or binary files. By mastering these techniques, you can enhance your file-handling skills in Java, making your applications more robust and efficient.
FAQ
- What is the best method to read integers from a text file in Java?
The best method often depends on your specific needs. For simple text files, usingBufferedReader
orScanner
is typically sufficient.
-
Can I read integers from a binary file in Java?
Yes, you can useFileInputStream
andDataInputStream
to read integers from binary files efficiently. -
How do I handle exceptions when reading files in Java?
Use try-catch blocks to handleIOException
orFileNotFoundException
, ensuring your program can gracefully manage errors. -
Is it necessary to close file streams in Java?
Yes, it’s important to close file streams to free up system resources. Using try-with-resources is a good practice. -
Can I read multiple integers from a single line in a file?
Yes, you can read multiple integers from a single line by splitting the line into tokens and parsing each token as an integer.
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn Facebook