Here you can find the source of getContent(File file, String charsetName)
Parameter | Description |
---|---|
file | the File |
charsetName | The name of a supported java.nio.charset.Charset </code>charset<code> |
Parameter | Description |
---|---|
IOException | if the File can't be read |
public static String getContent(File file, String charsetName) throws IOException
//package com.java2s; /******************************************************************************* * Copyright (c) 2015 Obeo.// w ww.j a v a 2 s .com * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Obeo - initial API and implementation and/or initial documentation * ... *******************************************************************************/ import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class Main { /** * Gets the content of the given {@link File}. * * @param file * the {@link File} * @param charsetName * The name of a supported {@link java.nio.charset.Charset </code>charset<code>} * @return a {@link String} of the content of the given {@link File} * @throws IOException * if the {@link File} can't be read */ public static String getContent(File file, String charsetName) throws IOException { if (!file.exists()) { throw new IOException(file.getAbsolutePath() + " doesn't exists."); } else if (file.isDirectory()) { throw new IOException(file.getAbsolutePath() + " is a directory."); } else if (!file.canRead()) { throw new IOException(file.getAbsolutePath() + " is not readable."); } int len = (int) file.length(); final String res; if (len != 0) { res = getContent(len, new FileInputStream(file)); } else { res = ""; } return res; } /** * Gets the content of the given {@link File}. * * @param length * the {@link InputStream} size * @param inputStream * the {@link InputStream} * @return a {@link String} of the content of the given {@link File} * @throws IOException * if the {@link InputStream} can't be read */ public static String getContent(int length, InputStream inputStream) throws IOException { final StringBuilder res = new StringBuilder(length); final InputStreamReader input = new InputStreamReader(new BufferedInputStream(inputStream)); final char[] buffer = new char[length]; int len = input.read(buffer); while (len != -1) { res.append(buffer, 0, len); len = input.read(buffer); } input.close(); return res.toString(); } }