Konstantina Dimtsa

About Konstantina Dimtsa

Konstantina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she is currently pursuing M.Sc studies in Advanced Information Systems at the same department. She is also working as a research associate for NKUA in the field of telecommunications. Her main interests lie in software engineering, web applications, databases and telecommunications.

Java read file Example

In this example we will show how to open and read a file in Java. There are many ways to do this, but we will show two of them. For this example, we will read the contents of a text file named “test_file.txt”.

1. Read a file using BufferedReader

This is the most commonly-used method in order to read a file in Java. BufferedReader reads text from a character-input stream, buffering the characters for the more efficient reading of characters, arrays, and lines.

Create a java class named ReadFileBufferedReader.java with the following code:

ReadFileBufferedReader.java

package com.javacodegeeks.javaio.readfile;

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

public class ReadFileBufferedReader {

	private static String filepath = "/home/konstantina/test_file.txt";

	public static void main(String[] args) {

		BufferedReader br;
		String curline;
		try {
			br = new BufferedReader(new FileReader(filepath));

			while ((curline = br.readLine()) != null) {
				System.out.println(curline);
			}

			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

In this case, we used the class FileReader along with BufferedReader. FileReader needs the file’s name and path so as to open the file. The BufferedReader class provides a method named readLine() so as to read each line of the file. There is a while loop which is executed till readLine() reaches the end of the file.

If we run the above code, we will see the contents of the file “test_file.txt”.

  • Output:
This is a test file.
Read file example
provided by
examples.javacodegeeks.com

2. Read a file using FileInputStream

This is another way of reading a file. FileInputStream reads streams of raw bytes from a file. So, we need to convert those bytes to characters in order to display the contents of the file to the screen.

Create a java class named ReadFileInputStream.java with the following code:

ReadFileInputStream.java

package com.javacodegeeks.javaio.readfile;

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

public class ReadFileInputStream {

	private static String filepath = "/home/konstantina/test_file.txt";

	public static void main(String[] args) {

		try {
			File file = new File(filepath);

			FileInputStream in = new FileInputStream(file);

			System.out.println("Total bytes to read from file : "
					+ in.available());

			int i;
			StringBuffer buf = new StringBuffer("");

			while ((i = in.read()) != -1) {
				// convert byte to char and append to StringBuffer
				buf.append((char) i);

			}

			in.close();

			System.out.println("File contents :");
			System.out.println(buf);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

If we run the above code, we will have the following results:

  • Output:
Total bytes to read from file : 78
File contents :
This is a test file.
Read file example
provided by
examples.javacodegeeks.com

3. Download the source code

You can download the source code of this example from here: ReadFileExample.zip

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books