Java InputStreamReader Create readTextFile(final File file)

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

Description

read Text File

License

Apache License

Declaration

public static String readTextFile(final File file) 

Method Source Code

//package com.java2s;
/*#######################################################
 *
 *   Maintained by Gregor Santner, 2017-
 *   https://gsantner.net///  ww  w.  ja v  a2s . c  o m
 *
 *   License: Apache 2.0
 *  https://github.com/gsantner/opoc/#licensing
 *  https://www.apache.org/licenses/LICENSE-2.0
 *
#########################################################*/

import java.io.BufferedReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static String readTextFile(final File file) {
        try {
            return readCloseTextStream(new FileInputStream(file));
        } catch (FileNotFoundException e) {
            System.err.println("readTextFile: File " + file + " not found.");
        }

        return "";
    }

    public static String readCloseTextStream(final InputStream stream) {
        return readCloseTextStream(stream, true).get(0);
    }

    public static List<String> readCloseTextStream(final InputStream stream, boolean concatToOneString) {
        final ArrayList<String> lines = new ArrayList<>();
        BufferedReader reader = null;
        String line = "";
        try {
            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(stream));

            while ((line = reader.readLine()) != null) {
                if (concatToOneString) {
                    sb.append(line).append('\n');
                } else {
                    lines.add(line);
                }
            }
            line = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (concatToOneString) {
            lines.clear();
            lines.add(line);
        }
        return lines;
    }
}

Related

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