Java Text File Read by Charset readFile(File file, Charset charset)

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

Description

read File

License

Open Source License

Return

the contents of the given file

Declaration

static String readFile(File file, Charset charset) throws IOException 

Method Source Code

//package com.java2s;
/*// www .  java2 s  .  co m
 * ----------------------------------------------------------------------------
 * "THE WINE-WARE LICENSE" Version 1.0:
 * Authors: Carmen Alvarez. 
 * As long as you retain this notice you can do whatever you want with this stuff. 
 * If we meet some day, and you think this stuff is worth it, you can buy me a 
 * glass of wine in return. 
 * 
 * THE AUTHORS OF THIS FILE ARE NOT RESPONSIBLE FOR LOSS OF LIFE, LIMBS, SELF-ESTEEM,
 * MONEY, RELATIONSHIPS, OR GENERAL MENTAL OR PHYSICAL HEALTH CAUSED BY THE
 * CONTENTS OF THIS FILE OR ANYTHING ELSE.
 * ----------------------------------------------------------------------------
 */

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

import java.nio.charset.Charset;

public class Main {
    /**
     * @return the contents of the given file
     */
    static String readFile(File file, Charset charset) throws IOException {
        InputStream is = new FileInputStream(file);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int read;
        try {
            while ((read = is.read(buffer)) != -1) {
                os.write(buffer, 0, read);
                os.flush();
            }
        } finally {
            is.close();
            os.close();
        }
        return os.toString(charset.name());
    }
}

Related

  1. reader(InputStream in, String charsetName)
  2. readerBuffered(final File file, final Charset charset)
  3. readFile(Bundle bundle, String path, Charset cs)
  4. readFile(File f, Charset chst)
  5. readFile(File file, Charset charset)
  6. readFile(File file, Charset cs)
  7. readFile(File file, String charsetName)
  8. readFile(File theFile, Charset theCharset)
  9. readFile(final InputStream is, final Charset encoding)