Java File Read by Charset getString(File file, Charset charset)

Here you can find the source of getString(File file, Charset charset)

Description

Reads a file into a string.

License

LGPL

Parameter

Parameter Description
file The file
charset The charset (null to use default JVM charset; not recommended!)

Exception

Parameter Description
IOException an exception

Return

The string read from the file

Declaration

public static String getString(File file, Charset charset) throws IOException 

Method Source Code

//package com.java2s;
/**//from   w  ww .j  av  a 2  s. co m
 * Copyright 2009-2012 Three Crickets LLC.
 * <p>
 * The contents of this file are subject to the terms of the LGPL version 3.0:
 * http://www.gnu.org/copyleft/lesser.html
 * <p>
 * Alternatively, you can obtain a royalty free commercial license with less
 * limitations, transferable or non-transferable, directly from Three Crickets
 * at http://threecrickets.com/
 */

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

import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class Main {
    /**
     * Reads a file into a string.
     * 
     * @param file
     *        The file
     * @param charset
     *        The charset (null to use default JVM charset; not recommended!)
     * @return The string read from the file
     * @throws IOException
     */
    public static String getString(File file, Charset charset) throws IOException {
        FileInputStream stream = new FileInputStream(file);
        try {
            FileChannel channel = stream.getChannel();
            try {
                MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
                if (charset == null)
                    charset = Charset.defaultCharset();
                return charset.decode(buffer).toString();
            } finally {
                channel.close();
            }
        } finally {
            stream.close();
        }
    }
}

Related

  1. getFileEncodingCharset()
  2. getFileText(File file, Charset charset)
  3. getNumberOfNonEmptyLines(File file, Charset charset)
  4. getPatchFileCharset()
  5. getPropertiesVaule(File file, String key, Charset charset)
  6. getUncommentedLines(File file, Charset forName)
  7. getZipFile(File src, Charset charset)
  8. isEqual(final File document, final Charset a, final Charset b)
  9. load(File file, Charset charset)