An easy tool to read a file and put all its content into a String. - Java java.io

Java examples for java.io:BufferedReader

Description

An easy tool to read a file and put all its content into a String.

Demo Code

//package com.java2s;
import java.io.BufferedReader;

import java.io.File;

import java.io.FileNotFoundException;
import java.io.FileReader;

import java.io.IOException;

import java.io.StringWriter;

public class Main {
    public static void main(String[] argv) {
        String filename = "Main.java";
        System.out.println(loadTextFileOnOneString(filename));
    }//  w  ww  .  ja v a  2  s  . c o m

    /**
     * An easy tool to read a file and put all its content into a String.
     * '\n' are removed from the text Removed.
     *
     * @param filename
     * @return
     */
    public static String loadTextFileOnOneString(String filename) {

        StringWriter writer = new StringWriter();

        try {
            BufferedReader reader = new BufferedReader(new FileReader(
                    new File(filename)));
            String line = reader.readLine();
            while (line != null) {
                writer.write(line);
                line = reader.readLine();
            }
            reader.close();
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        }

        return writer.toString();
    }
}

Related Tutorials