Reading a file is a task which every developer is required to perform. Java provides many different ways to read a file according to requirements. Below are listed various methods in which a file can be read in java.

Method 1: Using java.io.FileInputStream

static void readUsingStream(String filePath) { FileInputStream fin = null; //initialize the input byte array byte[] buffer = new byte[1024]; try { fin = new FileInputStream(new File(filePath)); int i = 0; while ((i = fin.read(buffer)) ! = -1) { System.out.println(new String(buffer)); } } catch (IOException e) { e.printStackTrace(); } finally { if (fin ! = null) { try { fin.close(); } catch (IOException e) { e.printStackTrace(); }}}}Copy the code

static void readUsingStream(String filePath) { FileInputStream fin = null; //initialize the input byte array byte[] buffer = new byte[1024]; try { fin = new FileInputStream(new File(filePath)); int i = 0; while ((i = fin.read(buffer)) ! = -1) { System.out.println(new String(buffer)); } } catch (IOException e) { e.printStackTrace(); } finally { if (fin ! = null) { try { fin.close(); } catch (IOException e) { e.printStackTrace(); }}}}

Detail : Initialize a java.io.FileInputStream with the source file as argument and a byte array which will hold all the bytes read by the stream. Iterate over read() method till it returns -1 which means that the end of file has reached. In each iteration, the stream reads the bytes from the file and writes them to the buffer. The buffer contents are converted to a String and written to console. At the end, do not forget to close the input stream.

Method 2: Using java.io.FileReader

static void readUsingFileReader(String filePath) { FileReader fr = null; char[] buffer = new char[1024]; try { fr = new FileReader(filePath); int i = 0; while ((i = fr.read(buffer)) ! = -1) { System.out.println(new String(buffer)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fin ! = null) { try { fin.close(); } catch (IOException e) { e.printStackTrace(); }}}}Copy the code

static void readUsingFileReader(String filePath) { FileReader fr = null; char[] buffer = new char[1024]; try { fr = new FileReader(filePath); int i = 0; while ((i = fr.read(buffer)) ! = -1) { System.out.println(new String(buffer)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fin ! = null) { try { fin.close(); } catch (IOException e) { e.printStackTrace(); }}}}

Detail : Initialize a java.io.FileReader with the source file as argument and a character array which will hold all the characters read by the stream. Iterate over read() method till it returns -1 which means that the end of file has reached. In each iteration, the file reader reads the characters from the file and writes them to the buffer. The characters from the buffer are converted to a String and written to console. At the end, do not forget to close the input reader.

Method 3: Using java.io.BufferedReader

Copy the code

static void readUsingBufferedReader(String filePath) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(filePath)); String str = null; while ((str = br.readLine()) ! = null) { System.out.println(str); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br ! = null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); }}}}

Detail : Initialize a java.io.BufferedReader object which takes a java.io.FileReader object as argument which is linked to the original file. Iterate over readLine() method till it returns -1 which means that the end of file has reached. At the end, do not forget to close the reader.

Method 4: Using Apache Commons library

static void usingApacheCommons(String filePath) { FileInputStream fin = null; try { StringWriter writer = new StringWriter(); fin = new FileInputStream(new File(filePath)); IOUtils.copy(fin, writer); System.out.println(writer.toString()); } catch (FileNotFoundException fne) { fne.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fin ! = null) { try { fin.close(); } catch (IOException e) { e.printStackTrace(); }}}}Copy the code

static void usingApacheCommons(String filePath) { FileInputStream fin = null; try { StringWriter writer = new StringWriter(); fin = new FileInputStream(new File(filePath)); IOUtils.copy(fin, writer); System.out.println(writer.toString()); } catch (FileNotFoundException fne) { fne.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fin ! = null) { try { fin.close(); } catch (IOException e) { e.printStackTrace(); }}}}

Detail : Initialize a java.io.FileInputStream object with the source file as argument. copy() method of IOUtils from Apache commons library takes an input stream and writes it to a writer. In this case we take a java.io.StringWriter. At the end, do not forget to close the input stream. This method requires Apache commons library to be on the classpath. Get it here

Method 5: Using java.io.Scanner

static void usingScanner(String filePath) { FileInputStream fin = null; byte[] buffer = new byte[1024]; Scanner scanner = null; try { fin = new FileInputStream(new File(filePath)); scanner = new Scanner(fin); scanner.useDelimiter("\\n"); while (scanner.hasNext()) { System.out.println(scanner.next()); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (scanner ! = null) { scanner.close(); }}}Copy the code

static void usingScanner(String filePath) { FileInputStream fin = null; byte[] buffer = new byte[1024]; Scanner scanner = null; try { fin = new FileInputStream(new File(filePath)); scanner = new Scanner(fin); scanner.useDelimiter(“\\n”); while (scanner.hasNext()) { System.out.println(scanner.next()); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (scanner ! = null) { scanner.close(); }}}

Detail : Initialize a java.io.FileInputStream with the source file as argument and a scanner object which is linked to this stream. A new line character is set as the delimiter for this scanner. If this line is omitted or a new line character is not used then the scanner will split the output on a white space and each word will be printed on a new line. At the end, do not forget to close the scanner.

Method 6: Using java.nio.channels.FileChannel (jdk 7 & above)

 static void usingChannel(String filePath) { RandomAccessFile fileAccess = null; FileChannel readChannel = null; try { fileAccess = new RandomAccessFile(new File(filePath), "r"); readChannel = fileAccess.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (readChannel.read(buffer) ! = -1) { buffer.flip(); for (int i = 0; i < buffer.limit(); i++) { System.out.print((char) buffer.get(i)); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fileAccess ! = null) { try { fileAccess.close(); } catch (IOException e) { e.printStackTrace(); }}}}Copy the code

static void usingChannel(String filePath) { RandomAccessFile fileAccess = null; FileChannel readChannel = null; try { fileAccess = new RandomAccessFile(new File(filePath), “r”); readChannel = fileAccess.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (readChannel.read(buffer) ! = -1) { buffer.flip(); for (int i = 0; i < buffer.limit(); i++) { System.out.print((char) buffer.get(i)); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fileAccess ! = null) { try { fileAccess.close(); } catch (IOException e) { e.printStackTrace(); }}}}

Detail : Initialize a java.io.RandomAccessFile.RandomAccessFile with the source file as argument. RandomAccessFile can be used to both read or write to a file. It takes an operation mode along with the file path as argument during initialization. Since we want to read the file, we set the mode as “R”, which means read mode. RamdomAccessFile opens a java.nio.channels.FileChannel through its getChannel() method. FileChannel reads the data using its read() method and writes it to a java.nio.ByteBuffer. FileChannel acts as a bridge between the file and storage buffer. Same buffer is used to hold the contents of file and for reading its contents. This Is done using buffer’s flip() method which resets the position of the buffer to 0. We extract the contents of the buffer in a loop and in every iteration a single byte is retrieved, converted to a character and written to the console. At the end, do not forget to close the fileAccess.

Note : All the above methods write the output from the file to console but they may also be written to another file. Java provides different methods for writing a file. Refer this post for details.

Let’s tweak in:

  1. All file reader and writer classes which directly interact with a file or a java.io.File object such as java.io.FileInputStream.java.io.FileReader.java.io.FileOutputStream throw a java.io.FileNotFoundException since there is always a risk of file location being invalid (either the file is not present or the location denotes a directory).
  2. All read() and write() methods throw a java.io.IOException since many kinds of errors may arise during both these operations such as file is corrupt, there are no write permissions, no disk space, file removed from its location etc.
  3. java.io.FileInputStream.java.io.FileReader both have constructors which take a java.io.File object or a file name in String format as arguments.
  4. java.io.FileInputStream operates over bytes and is more suitable for binary files such as images, jars etc. while java.io.FileReader deals with characters and is more suitable for text files.
  5. java.io.BufferedReader is faster as compared to java.io.FileInputStream and java.io.FileReaderas it reads a complete line in one go.
  6. read() method of all reader classes returns -1 when there is nothing left to read.
  7. Closing a java.io.BufferedReader closes the underlying java.io.Reader and there is no need to close it explicitly.Similarly, closing a java.io.Scanner closes the underlying java.io.InputStream and there is no need to close it explicitly. And closing java.io.RandomAccessFile also closes the underlying java.nio.channels.FileChannel
  8. If you are using jdk 7 and above for development and declare the stream or reader objects as try(FileInputStream fin = new FileInputStream(new File(filePath)))“And you don’t need to explicitly close the stream or readertry-with-resources construct.
  9. The default delimiter of scanner is a white space which means that it will split the input characters on a white space