Java FileReader Create readTextfile(final String filename)

Here you can find the source of readTextfile(final String filename)

Description

Reads a text file into a string.

License

Open Source License

Parameter

Parameter Description
filename The name of the text file.

Exception

Parameter Description
IOException an exception

Return

The text read from the file.

Declaration

public static String readTextfile(final String filename) throws IOException 

Method Source Code


//package com.java2s;
/*//www .  j  ava2  s . com
Copyright 2015 Google Inc. All Rights Reserved.
    
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    
http://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

public class Main {
    /**
     * Reads a text file into a string.
     *
     * @param file The file to read.
     * @return The text read from the file.
     *
     * @throws IOException
     */
    public static String readTextfile(final File file) throws IOException {
        final StringBuffer contents = new StringBuffer();

        final BufferedReader input = new BufferedReader(new FileReader(file));

        final String lineSeparator = System.getProperty("line.separator");

        try {
            String line = null;

            while ((line = input.readLine()) != null) {
                contents.append(line);
                contents.append(lineSeparator);
            }
        } finally {
            input.close();
        }

        return contents.toString();
    }

    /**
     * Reads a text file into a string.
     *
     * @param filename The name of the text file.
     * @return The text read from the file.
     *
     * @throws IOException
     */
    public static String readTextfile(final String filename) throws IOException {
        return readTextfile(new File(filename));
    }
}

Related

  1. readTextFile(File file)
  2. readTextFile(File file)
  3. readTextFile(File file)
  4. readTextFile(File file, boolean newline)
  5. readTextFile(File file, int header)
  6. readTextFile(InputStream in)
  7. readTextFile(InputStream in)
  8. readTextFile(String completePath)
  9. readTextFile(String file)