Java Text File Load loadTextFile(File file)

Here you can find the source of loadTextFile(File file)

Description

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

License

Open Source License

Parameter

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

Declaration

public static String loadTextFile(File file) throws IOException 

Method Source Code

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

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

public class Main {
    /**//ww  w.j a  va  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 file is a file which already exists and can be read.
     */
    public static String loadTextFile(File file) throws IOException {
        //...checks on file are elided
        StringBuffer contents = new StringBuffer();

        //use buffering, reading one line at a time
        //FileReader always assumes default encoding is OK!
        BufferedReader input = new BufferedReader(new FileReader(file));
        try {
            String line = null; //not declared within while loop
            /*
             * readLine is a bit quirky :
             * it returns the content of a line MINUS the newline.
             * it returns null only for the END of the stream.
             * it returns an empty String if two newlines appear in a row.
             */
            while ((line = input.readLine()) != null) {
                contents.append(line);
                contents.append(System.getProperty("line.separator"));
            }
        } finally {
            input.close();
        }

        return contents.toString();
    }
}

Related

  1. loadText(File file, int bufsize)
  2. loadText(java.io.File f)
  3. loadText(String fname)
  4. loadText(String path)
  5. loadText(String path)
  6. loadTextFile(File textFile)
  7. loadTextFile(final String filePath)
  8. loadTextFile(String fileFullPath)
  9. loadTextFile(String fileName)