Java Text File Load loadText(File file)

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

Description

This method wraps all the horrid Java 6 IO APIs for extracting a String from a text file.

License

Open Source License

Parameter

Parameter Description
file The text File to load.

Return

A String representation of the contents of the File

Declaration

public static String loadText(File file) 

Method Source Code


//package com.java2s;
//  the rights to use, copy, modify, merge, publish, distribute, sublicense, 

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.StringWriter;

public class Main {
    /**/*  w ww .j  a va  2 s. c o  m*/
     * This method wraps all the horrid Java 6 IO APIs for extracting a {@code String} from a text file.
     *
     * @param file The text {@code File} to load.
     *
     * @return A {@code String} representation of the contents of the {@code File}
     */
    public static String loadText(File file) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            StringWriter writer = new StringWriter();

            try {
                String line = reader.readLine();
                while (null != line) {
                    writer.append(line).append("\n");
                    line = reader.readLine();
                }

                return writer.toString();
            } finally {
                reader.close();
                writer.close();
            }
        } catch (Exception e) {
            e.printStackTrace();

            return "";
        }
    }
}

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)
  7. loadText(String path)