Java InputStreamReader Create readTextFile(final File f)

Here you can find the source of readTextFile(final File f)

Description

Read text file into a String.

License

Apache License

Declaration

public static String readTextFile(final File f) throws IOException 

Method Source Code

//package com.java2s;
/*/*  w ww  . j av a2  s  .  c  o m*/
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
    
http://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
    
Author(s) / Copyright (s): Damon Hart-Davis 2015
*/

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStreamReader;

public class Main {
    /**8-bit ISO-8859-1 file encoding. */
    public static final String FILE_ENCODING_8859_1 = "ISO-8859-1";

    /**Read text file into a String.
     * Reads a line at a time, trimming whitespace off either
     * end and putting in a single new line at the end instead.
     * <p>
     * This treats the file as ISO-8859-1 8-bit data.
     *
     * @exception IOException  in case of trouble
     */
    public static String readTextFile(final File f) throws IOException {
        final StringBuilder sb = new StringBuilder((int) f.length());
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(f), FILE_ENCODING_8859_1));
            String inputLine;
            while ((inputLine = br.readLine()) != null) {
                sb.append(inputLine.trim());
                sb.append('\n');
            }
        } finally {
            // Try to close the file (possibly provoking an exception)...
            if (br != null) {
                br.close();
                br = null;
            }
        }
        return (sb.toString());
    }
}

Related

  1. readTextFile(File file)
  2. readTextFile(File file, String charsetName)
  3. readTextFile(File fromFile)
  4. readTextFile(File inputFile)
  5. readTextFile(File path)
  6. readTextFile(final File file)
  7. ReadTextFile(InputStream is)
  8. readTextFile(java.io.File file)
  9. readTextFile(Reader reader)