Monday, April 30, 2018

Read data from a file using BufferedReader !!

Using BufferedReader:
  1. import java.io.File;
  2. import java.io.FileReader;
  3. import java.io.BufferedReader;

  4. public class ReadFileByBufferedReader {

  5. public static void main(String[] args) {
  6. try {
  7. File file = new File("D://data.txt");
  8. FileReader fr = new FileReader(file);
  9. BufferedReader br = new BufferedReader(fr);
  10. String line = br.readLine(); // read the line
  11. while (null != line) {
  12. System.out.println(line); // print the line
  13. line = br.readLine(); // read the next line
  14. }
  15. fr.close();
  16. } catch (Exception e) {
  17. System.out.println("excepton occured in " + e);
  18. }
  19. }
  20. }
Note: extension support .java/.txt/.xml/.yml/.html/.css etc file

Output:
Hi guys !!
This is Ishaan from India.
and I'm reading the data from a text file line by line using BufferedReader.
Isn't it interesting !! to read the data from a file line by line
irrespective of amount of data that a file is having.

II Approach:

  1. import java.io.File;
  2. import java.io.FileReader;
  3. import java.io.BufferedReader;

  4. public class ReadFileByBufferedReader {

  5. public static void main(String[] args) {
  6. File file = null;
  7. FileReader fr = null;
  8. BufferedReader br = null;
  9. try {
  10. file = new File("D://data.txt");
  11. fr = new FileReader(file);
  12. br = new BufferedReader(fr);
  13. String line = br.readLine(); // read the next line

  14. while (line != null) {
  15. System.out.println(line); // print the line
  16. line = br.readLine(); // read the next line
  17. }
  18. } catch (Exception e) {
  19. System.out.println("excepton occured in " + e);
  20. } finally {
  21. try {
  22. if (fr != null) {
  23. fr.close();
  24. }
  25. if (br != null) {
  26. br.close();
  27. }
  28. } catch (Exception e) {
  29. System.out.println("excepton occured in finally block " + e);
  30. }
  31. }
  32. }
  33. // support .java/.txt/.xml/.yml/.html/.css etc file
  34. }

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...