how to read text file in java using bufferedreader

Solutions on MaxInterview for how to read text file in java using bufferedreader by the best coders in the world

showing results for - "how to read text file in java using bufferedreader"
Lucille
25 Jan 2019
1package beginnersbook.com;
2import java.io.BufferedReader;
3import java.io.FileReader;
4import java.io.IOException;
5
6public class ReadFileDemo {
7   public static void main(String[] args) {
8
9       BufferedReader br = null;
10       BufferedReader br2 = null;
11       try{	
12           br = new BufferedReader(new FileReader("B:\\myfile.txt"));		
13
14           //One way of reading the file
15	   System.out.println("Reading the file using readLine() method:");
16	   String contentLine = br.readLine();
17	   while (contentLine != null) {
18	      System.out.println(contentLine);
19	      contentLine = br.readLine();
20	   }
21
22	   br2 = new BufferedReader(new FileReader("B:\\myfile2.txt"));
23
24	   //Second way of reading the file
25	   System.out.println("Reading the file using read() method:");
26	   int num=0;
27	   char ch;
28	   while((num=br2.read()) != -1)
29	   {	
30               ch=(char)num;
31	       System.out.print(ch);
32	   }
33
34       } 
35       catch (IOException ioe) 
36       {
37	   ioe.printStackTrace();
38       } 
39       finally 
40       {
41	   try {
42	      if (br != null)
43		 br.close();
44	      if (br2 != null)
45		 br2.close();
46	   } 
47	   catch (IOException ioe) 
48           {
49		System.out.println("Error in closing the BufferedReader");
50	   }
51	}
52   }
53}