How To Read Text File into String - Java @ Desk

Friday, March 21, 2014

How To Read Text File into String



How To Read Text File into String

We read a file in java using the java.io.BufferedReader class.

In the below example we will see how to read a file in java and convert the contents to String object.

File contains this string - Online Psychology Degree, Online Paralegal Degree, Insurances, Domain Names, Interior Design Degree, Bank Loans


package com.file;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileToString {
 public static void main(String[] args) throws IOException {

  BufferedReader bufferedReader = new BufferedReader(new FileReader("<FILE_PATH>"));
  String outputString = "";
  StringBuffer stringBuffer = new StringBuffer();

  while ((outputString = bufferedReader.readLine()) != null) {
   stringBuffer.append(outputString);
  }

  System.out.println(stringBuffer.toString());
 }
}


Also in Java 7, a utility method is provided which is quiet fast and efficient

byte[] encoded = Files.readAllBytes(Paths.get(path));
return encoding.decode(ByteBuffer.wrap(encoded)).toString();








No comments:

Post a Comment