Java Text File Load loadText(File file)

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

Description

Load a text file as a single string.

License

Open Source License

Parameter

Parameter Description
file The file.

Exception

Parameter Description
IOException For errors.

Return

The text as a string.

Declaration

public static String loadText(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.FileInputStream;

import java.io.IOException;

import java.io.InputStreamReader;

public class Main {
    /**/*from ww w.ja  va 2 s.c o  m*/
     * Load a text file as a single string. The contents of the file are normalized, in that line
     * breaks are always a single newline character ('\n'), regardless of the operating system.
     * 
     * @param file
     *            The file.
     * @return The text as a string.
     * @throws IOException
     *             For errors.
     */
    public static String loadText(File file) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = read(file);
        try {
            String line = br.readLine();
            while (line != null) {
                sb.append(line);
                line = br.readLine();
                if (line != null) {
                    sb.append('\n');
                }
            }
        } finally {
            br.close();
        }
        return sb.toString();
    }

    /**
     * Open UTF-8 input stream to target file.
     * 
     * @param file
     *            The file.
     * @return The stream.
     * @throws IOException
     *             For errors.
     */
    public static BufferedReader read(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis, "utf-8");
        return new BufferedReader(isr);
    }
}

Related

  1. loadText(File f)
  2. loadText(File file)
  3. loadText(File file)
  4. loadText(File file, int bufsize)
  5. loadText(java.io.File f)
  6. loadText(String fname)