Java Text File Read getFileContents(String filePath)

Here you can find the source of getFileContents(String filePath)

Description

Fetch the entire contents of a text file, and return it in a String.

License

Open Source License

Parameter

Parameter Description
aFile is a file which already exists and can be read.

Declaration

public static String getFileContents(String filePath) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedReader;
import java.io.File;

import java.io.FileReader;

public class Main {
    /**/* w  ww. j  a  v  a 2  s . co  m*/
     * Fetch the entire contents of a text file, and return it in a String.
     * This style of implementation does not throw Exceptions to the caller.
     *
     * @param aFile is a file which already exists and can be read.
     */
    public static String getFileContents(String filePath) throws Exception {
        StringBuffer contents = new StringBuffer();

        BufferedReader input = null;
        //use buffering
        //this implementation reads one line at a time
        input = new BufferedReader(new FileReader(new File(filePath)));
        String line = null; //not declared within while loop
        while ((line = input.readLine()) != null) {
            contents.append(line);
            contents.append(System.getProperty("line.separator"));
        }
        return contents.toString();
    }
}

Related

  1. getFileContentAsString(String path)
  2. getFileContents(Reader reader)
  3. getFileContents(String filePath)
  4. getFileContents(String filePath)
  5. getFileContents(String filePath)
  6. getFileContents(String path)
  7. getFileContents(String pathToFile)
  8. getFileContents(String pFileName)
  9. loadAsString(String location)