Java InputStreamReader Create readTextFile(File file)

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

Description

read Text File

License

Open Source License

Declaration

static public String readTextFile(File file) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

import java.io.InputStreamReader;

import java.io.StringWriter;

public class Main {
    static public String readTextFile(File file) throws Exception {
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {/*ww  w . ja  v a 2 s  .c o  m*/
            StringWriter sw = new StringWriter();
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis, "UTF-8");
            br = new BufferedReader(isr);

            char[] data = new char[1024];
            int size = br.read(data);
            while (size >= 0) {
                sw.write(data, 0, size);
                size = br.read(data);
            }
            sw.flush();

            fis.close();
            fis = null;
            isr.close();
            isr = null;
            br.close();
            br = null;

            return sw.toString();

        } catch (Exception e) {
            throw new Exception("Error while reading text file: " + file, e);

        } finally {
            if (isr != null) {
                try {
                    isr.close();
                    isr = null;
                } catch (Exception e) {
                    // Ignore
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                    fis = null;
                } catch (Exception e) {
                    // Ignore
                }
            }
            if (br != null) {
                try {
                    br.close();
                    br = null;
                } catch (Exception e) {
                    // Ignore
                }
            }
        }
    }
}

Related

  1. readTextFile(File f)
  2. readTextFile(File f)
  3. readTextFile(File f)
  4. readTextFile(File f)
  5. readTextFile(File f, int maxNumLines)
  6. readTextFile(File file)
  7. readTextFile(File file, String charsetName)
  8. readTextFile(File fromFile)
  9. readTextFile(File inputFile)