How to assign file content to a String in Java

Question:
How to copy the content of a file to a String using Java?

Code:
import java.io.DataInputStream;
import java.io.FileInputStream;
 
public class FileToString {
 
   public static void main(String args[]) {
 
      try {
 
         FileInputStream fis = new FileInputStream("/tmp/myfile.txt");
         DataInputStream dis = new DataInputStream(fis);
 
         byte[] data = new byte[dis.available()];
         dis.readFully(data);
         dis.close();
 
         String content = new String(data, 0, data.length);
 
         System.out.println(content);
 
      } catch (Exception ex) {
         System.out.println(ex);
      }
 
   }
}

Output:
$ java FileToString
This is an example on how to copy the contents of a file to a String using Java.



$ cat myfile.txt
This is an example on how to copy the contents of a file to a String using Java.