Reading data from a text file in Java

If you are reading a text file, you can use the FileReader class in the java.io package. Here’s an example:

import java.io.*;
 
public class Main {
   public static void main(String []args) {
      if (args.length != 1) {
         System.out.println("Usage: java Main <textfile>");
         System.exit(1);
      }
  
      try {
         String line;
         BufferedReader br = new BufferedReader(new FileReader(args[0]));
         while ((line = br.readLine()) != null) {
            System.out.println(line);
         }
      }
      catch (IOException e) {
         System.out.println(e);
      }
   }
}

You will probably still see code around that uses the method readLine of the DataInputStream class. Sun has deprecated this method because it does not properly convert bytes (1 byte) to characters (2 bytes). Here’s the code if you’re still using 1.0.2:

import java.io.*;
 
public class Main {
   public static void main(String []args) {
      if (args.length != 1) {
         System.out.println("Usage: java Main <textfile>");
         System.exit(1);
      }
  
      try {
         String line;
         DataInputStream dis = new DataInputStream(new FileInputStream(args[0]));
         while ((line = dis.readLine()) != null) {
            System.out.println(line);
         }
      }
      catch (IOException e) {
         System.out.println(e);
      }
   }
}