Java InputStreamReader Create readTextFile(String filePath, String charset)

Here you can find the source of readTextFile(String filePath, String charset)

Description

read Text File

License

Apache License

Declaration

public static ArrayList<String> readTextFile(String filePath, String charset) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.BufferedReader;

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

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.ArrayList;

public class Main {
    public static ArrayList<String> readTextFile(String filePath, String charset) {
        if (!checkFile(filePath, false)) {
            return null;
        }//from  w w  w . ja  v  a  2 s. co m
        ArrayList<String> data = new ArrayList<String>();
        FileInputStream in = null;
        BufferedReader r = null;
        try {
            in = new FileInputStream(filePath);
            r = new BufferedReader(new InputStreamReader(in, charset));
            String read;
            while ((read = r.readLine()) != null) {
                data.add(read);
            }
        } catch (IOException ex) {
            return null;
        } finally {
            try {
                if (r != null)
                    r.close();
                if (in != null)
                    in.close();
            } catch (IOException ex) {
            }
        }
        return data;
    }

    public static boolean checkFile(String file, boolean create) {
        File f = new File(file);

        if (f.getParent() != null) {
            File fpath = new File(f.getParent());
            if (!fpath.exists()) {
                if (create) {
                    fpath.mkdirs();
                } else {
                    return false;
                }
            }
        }
        if (!f.exists()) {
            if (create) {
                try {
                    f.createNewFile();
                } catch (IOException e) {
                    return false;
                }
            } else {
                return false;
            }
        }
        return true;
    }
}

Related

  1. ReadTextFile(InputStream is)
  2. readTextFile(java.io.File file)
  3. readTextFile(Reader reader)
  4. readTextFile(String fileName)
  5. readTextFile(String filename, int maxNumLines, boolean startAtBeginning)
  6. readTextFile(String fullPathFilename)
  7. readTextFile(String realPath)
  8. readTextFileAsStringArray(final File file, final String charSet)