Java File Read by Charset getFileContent(File file, String charsetName)

Here you can find the source of getFileContent(File file, String charsetName)

Description

get File Content

License

Open Source License

Declaration

public static String getFileContent(File file, String charsetName) 

Method Source Code


//package com.java2s;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;

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

import java.nio.channels.FileChannel;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import java.nio.charset.UnmappableCharacterException;

public class Main {

    public static String getFileContent(File file) {
        return getFileContent(file, Charset.defaultCharset().displayName());
    }//from ww w.j  ava2 s  .co m

    public static String getFileContent(File file, String charsetName) {
        if (file.isFile()) {
            FileInputStream inf = null;
            FileChannel inc = null;
            StringBuilder content = new StringBuilder();
            try {
                inf = new FileInputStream(file);
                inc = inf.getChannel();
                Charset charset = Charset.forName(charsetName);
                CharsetDecoder decoder = charset.newDecoder();
                InputStreamReader reader = new InputStreamReader(inf, decoder);
                char cbuf[] = new char[1024];
                int count = 0;
                while ((count = reader.read(cbuf)) > -1) {
                    content.append(cbuf, 0, count);
                }

                return content.toString();
            } catch (UnmappableCharacterException e) {
                System.err.println("The file's charset is not " + charsetName + ". file:" + file.getAbsolutePath());
                // e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                close(inc);
                close(inf);
            }
        } else {
            // logger.warn("The file is not exists or is not a file!" + file.getAbsolutePath());
        }

        return "";
    }

    public static void close(Closeable c) {
        if (null != c) {
            try {
                c.close();
                c = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Related

  1. fileToString(final Path path, final Charset charset)
  2. findPattern(File file, Charset charset, String patternString)
  3. fixture(String filename, Charset charset)
  4. getContent(File file, String charsetName)
  5. getEOL(File file, Charset charset)
  6. getFileContents(File file, String charset)
  7. getFileEncodingCharset()
  8. getFileText(File file, Charset charset)
  9. getNumberOfNonEmptyLines(File file, Charset charset)