Home » Java programs

Java program to read characters from the file

In this java program, we will learn how to read characters from a file? Here, we are using ‘FileReader’ class and its method ‘read’ to read the characters from the file.
Submitted by IncludeHelp, on October 16, 2017

To read a single character from a file we are using "FileReader" class, see the code, here we are passing file name while creating an object of FileReader class, the statement is FileReader F = new FileReader("E:/IncludeHelp.txt"); Here, "Includehelp.txt" is the file name, from where we have to read characters.

Method "F.read()" is using to read characters from the file. Here, "F" is the object of "FileReader" class.

Consider the program to read characters from the file in Java

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

public class Read_Char 
{
	public static void main(String[] args) 
	{
		try
		{
			//Here F is the obeject of the file from which 
			//we have to read character and we have also mention 
			//the path of the given file.
			FileReader F=new FileReader("E:/IncludeHelp.txt");

			int b;

			//This loop will read characters and found 
			//character will be stored in b.
			while((b=F.read())!=-1)
			{
				// Will print the Characters...
				System.out.print((char)b);
			}

			// This will close the opened file. 
			F.close();
		}
		catch(IOException e)
		{
			// Will print the error if occurs during the process.
			System.out.println(e);	
		}
	}
}

Output

Include Help Works for you.

In the following program we take a file along with its path named (E:/IncludeHelp.txt ) to read char from that file, now we are going to apply the condition to search char from the given file, at this stage if there are some characters in that file then they will be printed. Sometimes there is the condition that the searched file is not present in the directory or in our system then it will generate the error. So we have to mention the correct path and the file name.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.