How do I create a Java string from the contents of a file?

Java 8Object Oriented ProgrammingProgramming

You can read contents of a file using the read() method of the class FileInputStream. To this method you need to pass a byte array as a parameter to which the contents of the file are to be read.

To convert a byte array to Sting simply pass the byte array as a parameter to the constructor of the String class.

Example

import java.io.File;
import java.io.FileInputStream;
public class Demo {
   public static void main(String args[]) throws Exception {
     
      File file = new File("data.txt");
      FileInputStream fis = new FileInputStream(file);
      byte[] bytesArray = new byte[(int)file.length()];
      fis.read(bytesArray);
      String s = new String(bytesArray);
      System.out.println(s);
   }
}

Output

Krishna Kasyap
raja
Published on 10-Jan-2018 10:09:57
Advertisements