Java I/O How to - Read full file content to string








Question

We would like to know how to read full file content to string.

Answer

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
//from  w  w  w .  j  av a2s  .  co m

public class Main{
  /**
   * Converts a file to a string
   * @param f The file
   * @return The string
   * @throws IOException Thrown in any IOException occurs
   */
  public static String fileToString(File f) throws IOException {
      ArrayList<String> list = new ArrayList<>(Files.readAllLines(f.toPath()));
      StringBuilder builder = new StringBuilder();
      list.forEach(builder::append);
      return builder.toString();
  }
}