Java Read Files

Java is a popular programming language used for a wide range of applications, including file handling. In this blog, we will explore how to read files in Java, including how to read text files and binary files, and provide example code snippets to illustrate each concept.

Reading Text Files in Java:

To read text files in Java, you can use the BufferedReader class. Here is an example:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadTextFile {
   public static void main(String[] args) {
      try {
         BufferedReader reader = new BufferedReader(new FileReader("filename.txt"));
         String line = reader.readLine();
         while (line != null) {
            System.out.println(line);
            line = reader.readLine();
         }
         reader.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

In the above example, we declare a BufferedReader object called reader and initialize it with a FileReader object. We then read each line of the text file using the readLine() method, print it using the System.out.println() method, and continue until there are no more lines to read. Finally, we close the BufferedReader object using the close() method.

Reading Binary Files in Java:

To read binary files in Java, you can use the FileInputStream class. Here is an example:

import java.io.FileInputStream;
import java.io.IOException;

public class ReadBinaryFile {
   public static void main(String[] args) {
      try {
         FileInputStream fileInputStream = new FileInputStream("filename.bin");
         int byteRead = fileInputStream.read();
         while (byteRead != -1) {
            System.out.print((char) byteRead);
            byteRead = fileInputStream.read();
         }
         fileInputStream.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

In the above example, we declare a FileInputStream object called fileInputStream and initialize it with the name of the binary file. We then read each byte of the file using the read() method, convert it to a character using the (char) cast, and print it using the System.out.print() method. Finally, we close the FileInputStream object using the close() method.

Conclusion:

Java provides a powerful set of tools for reading files, including text files and binary files. In this blog, we explored how to read files in Java, including how to use the BufferedReader class to read text files, and how to use the FileInputStream class to read binary files. We also provided example code snippets to illustrate each concept. By understanding how to read files in Java, you can make your programs more versatile and efficient.