Java "file open" and "file read" methods (examples)

Java file reading FAQ: Can you share some off-the-shelf Java methods I can use to open and read files in Java?

Sure. Taken directly from my Java file utilities article (Java file utilities to open, read, write, and copy files), here is the source code for two Java methods that let you read a text file.

1) Java - open and read file, return as one String

My first Java method lets you read a text file as one String:

/**
 * Opens and reads a file, and returns the contents as one String.
 */
public static String readFileAsString(String filename) 
throws IOException
{
  BufferedReader reader = new BufferedReader(new FileReader(filename));
  String line;
  StringBuilder sb = new StringBuilder();
  while ((line = reader.readLine()) != null)
  {
    sb.append(line + "\n");
  }
  reader.close();
  return sb.toString();
}

2) Java - open and read file, return as a List of Strings

My second Java file-reading method lets you open and read a file as a List of String objects:

/**
 * Open and read a file, and return the lines in the file as a list of
 * Strings.
 */
public static List<String> readFileAsListOfStrings(String filename) throws Exception
{
  List<String> records = new ArrayList<String>();
  BufferedReader reader = new BufferedReader(new FileReader(filename));
  String line;
  while ((line = reader.readLine()) != null)
  {
    records.add(line);
  }
  reader.close();
  return records;
}

Java file open and reading methods - Summary

I hope these Java "file open and read" examples will help in your own Java file-programming efforts. As you can see, one of the secrets is knowing how to use the BufferedReader class, which I've detailed in my Java BufferedReader examples.

Post new comment

The content of this field is kept private and will not be shown publicly.