Java Text File Read by Charset getFileContent(IFile file, String charset)

Here you can find the source of getFileContent(IFile file, String charset)

Description

Returns the file content as UTF8 string.

License

Apache License

Parameter

Parameter Description
file a parameter
charset a parameter

Declaration

public static String getFileContent(IFile file, String charset) 

Method Source Code

//package com.java2s;
/*/*  w  ww .jav a  2 s .  c  o m*/
 * Copyright (C) 2003-2014  Pascal Essiembre
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.eclipse.core.resources.IFile;

public class Main {
    /**
     * Returns the file content as UTF8 string.
     * 
     * @param file
     * @param charset 
     * @return
     */
    public static String getFileContent(IFile file, String charset) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        InputStream in = null;
        try {
            in = file.getContents(true);
            byte[] buf = new byte[8000];
            for (int count; (count = in.read(buf)) != -1;)
                outputStream.write(buf, 0, count);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignore) {
                }
            }
        }
        try {
            return outputStream.toString(charset);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return outputStream.toString();
        }
    }
}

Related

  1. createBOMStrippedReader(InputStream stream, String defaultCharset)
  2. createBufferedReaderWithGuessedCharset(File file)
  3. createInputStreamReader(File file, String charsetName)
  4. createReader(Path p, Charset cs)
  5. getDecoder(Charset charset, ThreadLocal> localDecoder)
  6. getInputStreamReader(InputStream stream, Charset charset)
  7. getReader(InputStream in, String charsetName)
  8. getReader(InputStream is, String charset)
  9. getReader(String fileName, Charset cs)