Java Text File Read by Encode readFileAsString(final File f, final String encoding)

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

Description

Read a file into a string using the specified encoding.

License

LGPL

Parameter

Parameter Description
f a parameter
encoding a parameter

Exception

Parameter Description
Exception an exception

Declaration

static String readFileAsString(final File f, final String encoding) throws Exception 

Method Source Code


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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;

public class Main {
    static void readFileAsString(final Appendable o, final File f) throws Exception {
        LineNumberReader lr = new LineNumberReader(new FileReader(f));
        try {//from  w  w w. j  ava 2 s.  co m
            String line;
            while (null != (line = lr.readLine())) {
                o.append(line);
                o.append("\n");
            }
        } finally {
            lr.close();
        }
    }

    /**
     * Read a file into a string using the specified encoding.
     *
     * @param f
     * @param encoding
     * @return
     * @throws Exception
     */
    static String readFileAsString(final File f, final String encoding) throws Exception {
        InputStream is = null;
        try {
            is = new FileInputStream(f);
            return readStreamAsString(is, encoding);
        } finally {
            if (is != null)
                is.close();
        }
    }

    static String readStreamAsString(final InputStream is, final String enc) throws Exception {
        StringBuilder sb = new StringBuilder(128);
        readStreamAsString(sb, is, enc);
        return sb.toString();
    }

    static void readStreamAsString(final Appendable o, final InputStream f, final String enc) throws Exception {
        Reader r = new InputStreamReader(f, enc);
        readStreamAsString(o, r);
    }

    static void readStreamAsString(final Appendable o, final Reader r) throws Exception {
        char[] buf = new char[4096];
        for (;;) {
            int ct = r.read(buf);
            if (ct < 0)
                break;
            o.append(new String(buf, 0, ct));
        }
    }
}

Related

  1. getFileContentAsString(File file, String encoding)
  2. getFileContentAsString(File file, String encoding)
  3. getFileContentAsString(String filePath, String fileEncoding)
  4. getFileContents(InputStream stream, String encoding)
  5. getFileContents(String filename, String encoding)
  6. readFileAsString(InputStream input, OutputStream output, String inputEncoding)