Here you can find the source of getString(File file, Charset charset)
Parameter | Description |
---|---|
file | The file |
charset | The charset (null to use default JVM charset; not recommended!) |
Parameter | Description |
---|---|
IOException | an exception |
public static String getString(File file, Charset charset) throws IOException
//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(); } } }