How to read data in from a file to String using java?


In Java you can read the contents of a file in several ways one way is to read it to a string using the java.util.Scanner class, to do so,

  • Instantiate the Scanner class, with the path of the file to be read, as a parameter to its constructor.

  • Create an empty String buffer.

  • Start a while loop with condition, if the Scanner has next line. i.e. hasNextLine() at while.

  • Within the loop append each line of the file to the StringBuffer object using the append() method.

  • Convert the contents of the contents of the buffer to String using the toString() method.

Create a file with name sample.txt in the C directory in your system, copy and paste the following content in it.

Tutorials Point is an E-learning company that set out on its journey to provide
knowledge to that class of readers that responds better to online content. With
Tutorials Point, you can learn at your own pace, in your own space.

After a successful journey of providing the best learning content at
tutorialspoint.com, we created our subscription based premium product called
Tutorix to provide Simply Easy Learning in the best personalized way for K-12
students, and aspirants of competitive exams like IIT/JEE and NEET.

Following Java program reads the contents of the file sample.txt in to a String and prints it.

Example

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class FileToString {
   public static void main(String[] args) throws IOException {
      Scanner sc = new Scanner(new File("E://test//sample.txt"));
      String input;
      StringBuffer sb = new StringBuffer();
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         sb.append(" "+input);
      }
      System.out.println("Contents of the file are: "+sb.toString());
   }
}

Output

Contents of the file are: Tutorials Point is an E-learning company that set out on its journey to provide
knowledge to that class of readers that responds better to online content. With Tutorials Point, you can
learn at your own pace, in your own space. After a successful journey of providing the best learning content
at tutorialspoint.com, we created our subscription based premium product called Tutorix to provide Simply
Easy Learning in the best personalized way for K-12 students, and aspirants of competitive exams like
IIT/JEE and NEET.

Updated on: 29-Jun-2020

424 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements