Java Text File Read by Encoding readFileAsString(File file, String encoding)

Here you can find the source of readFileAsString(File file, String encoding)

Description

read File As String

License

Open Source License

Declaration

public static String readFileAsString(File file, String encoding) 

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.IOException;

import java.io.InputStreamReader;

import java.util.ArrayList;

public class Main {
    public static final String NEW_LINE_CHARACTER = System.getProperty("line.separator");

    public static String readFileAsString(String file) {
        return readFileAsString(new File(file), "UTF8");
    }/*from www  .  j  a  va  2  s . com*/

    public static String readFileAsString(File file) {
        return readFileAsString(file, "UTF8");
    }

    public static String readFileAsString(File file, String encoding) {
        StringBuilder sb = new StringBuilder();
        ArrayList<String> lines = readFile(file, encoding);
        for (String line : lines) {
            sb.append(line).append(NEW_LINE_CHARACTER);
        }
        return new String(sb);
    }

    public static ArrayList<String> readFile(File file) {
        return readFile(file, "UTF8");
    }

    public static ArrayList<String> readFile(File file, String encoding) {
        ArrayList<String> lines = new ArrayList<String>(50);
        if (!file.exists()) {
            throw new IllegalStateException("Unable to find File " + file + " bye");
        } //if
        String line;
        boolean end = false;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
            while (!end) {
                line = br.readLine();
                if (line == null) {
                    end = true;
                } else {
                    lines.add(line);
                }
            } //while
            br.close();
        } //try
        catch (IOException ioe) {
            System.err.println("Unable to open file");
            System.exit(-1);
        }
        return lines;
    }
}

Related

  1. readFileAsString(File file, String encoding)
  2. readTextFile(File f, String fileEncoding)
  3. readTextFile(File file, String encoding)
  4. readTextFile(File file, String encoding)