java

How to Read a File Character by Character in Java

In this tutorial, we are going to see how to read a file character by character in Java using BufferedReader to read the content of the text file.
 

How to Read a File Character by Character in Java
import java.io.*;

public class Main 
{
   public static void main(String[] args) throws IOException 
   {
      // The input file
      File file = new File("file.txt");
      // Create the File Reader object
      FileReader fr = new FileReader(file);
      // Create the BufferedReader object
      BufferedReader br = new BufferedReader(fr);  
      int c = 0;             
      // Read character by character
      while((c = br.read()) != -1)
      {
            // convert the integer to char
            char ch = (char) c;         
            // Print the character		
            System.out.println(ch);        
      }
   }
}

Output:

S
t
a
c
k
H
o
w
T
o
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *