How to Read in a File in Java

Reading a file in Java is a fundamental task for many applications.

It is essential for reading and processing data from different sources, such as text, binary, and CSV files.

In this article, we will discuss the different ways to read a file in Java and provide code examples to help you get started.

Java provides several classes and methods to read files, making it easy to read and process data.

The File and FileReader classes are commonly used to read text files, while the FileInputStream and DataInputStream classes are used to read binary files.

Further, the CSV (Comma Separated Values) file format is widely used to store and exchange data, and the Scanner class can be used to read CSV files.


Reading a Text File

The File and FileReader classes are used to read text files. The File class represents a file or directory on the file system, while the FileReader class reads characters from a file.

Here’s an example of how to read a text file using the FileReader class:

File file = new File("example.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);

String line;
while((line = br.readLine()) != null){
    System.out.println(line);
}
br.close();

In this example, we first create an instance of the File class, passing the file path as an argument.

Next, we create an instance of the FileReader class, passing the File object as an argument. Finally, we use a while loop to read the file line by line and print each line to the console.

The BufferedReader class can be used to improve the performance of reading a text file.

The BufferedReader class reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

Here’s an example of how to read a text file using the BufferedReader class:

File file = new File("example.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);

String line;
while((line = br.readLine()) != null){
    System.out.println(line);
}
br.close();

Reading a Binary File

The FileInputStream and DataInputStream classes are used to read binary files.

The FileInputStream class reads bytes from a file, while the DataInputStream class reads primitive data types.

Here’s an example of how to read a binary file using the FileInputStream class:

FileInputStream fis = new FileInputStream("example.bin");
int b;
while((b = fis.read()) != -1){
    System.out.print(b + " ");
}
fis.close();

In this example, we first create an instance of the FileInputStream class, passing the file path as an argument.

Next, we use a while loop to read the file byte by byte and print each byte to the console.

Here’s an example of how to read a binary file using the DataInputStream class:

File file = new File("example.bin");
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fis);

int i = dis.readInt();
System.out.println(i);

Reading a CSV File

The CSV (Comma Separated Values) file format is widely used to store and exchange data.

The Scanner class can be used to read CSV files, but it can be a bit cumbersome to use for complex CSV files.

To handle complex CSV files, a third-party library such as OpenCSV can be used.

Here’s an example of how to read a CSV file using the Scanner class:

Scanner scanner = new Scanner(new File("example.csv"));
scanner.useDelimiter(",");
while(scanner.hasNext()){
    System.out.print(scanner.next() + " ");
}
scanner.close();

In this example, we first create an instance of the Scanner class, passing the file path as an argument.

Next, we set the delimiter to “,” to separate the values in the CSV file. Finally, we use a while loop to read the file and print each value to the console.

Using a third-party library such as OpenCSV, reading and writing CSV files is quite simple. Here’s an example of how to read a CSV file using OpenCSV:

String csvFile = "example.csv";
CSVReader reader = new CSVReader(new FileReader(csvFile));
String[] line;
while ((line = reader.readNext()) != null) {
    System.out.println(Arrays.toString(line));
}
reader.close();

Advanced Topics

Reading large files can be a challenging task, but Java provides several methods to handle large files efficiently.

One common method is to read the file in chunks and process the data in smaller batches.

Additionally, it is possible to read files from a remote location using the URL and URLConnection classes.

Another advanced topic is the use of parallel streams to read multiple files at once.

The parallelStream() method is used to create a parallel stream from a collection, and it can be used to process multiple files simultaneously, which can improve performance.


Conclusion

In this article, we discussed the different ways to read a file in Java, including text files, binary files, and CSV files.

We provided code examples to help you get started and discussed advanced topics such as reading large files and the use of parallel streams.

Keep in mind that the best method to read a file depends on the type of file and the specific requirements of your application.