Java Program to Create String from Contents of a File

Java Programming Java8Object Oriented Programming

The java.io.BufferedReader.readline() method read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Example

Following program reads the contents of a file to a string variable −

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

public class BufferedReaderDemo {
   public static void main(String[] args) throws Exception {
      String thisLine = null;

      try {
         // open input stream test.txt for reading purpose.
         BufferedReader br = new BufferedReader("c:/test.txt");

         while ((thisLine = br.readLine()) != null) {
            System.out.println(thisLine);
         }
      }  catch(Exception e) {
         e.printStackTrace();
      }
   }
}


Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program −

ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz

Output

ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
raja
Published on 26-Apr-2018 15:00:52
Advertisements