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

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

Description

read Chars With Encoding

License

Open Source License

Declaration

public static char[] readCharsWithEncoding(File file, Charset charset) throws IOException 

Method Source Code

//package com.java2s;
/*/* www .  j  a  v a2  s. c  o  m*/
 * net/balusc/util/FileUtil.java
 * 
 * Copyright (C) 2007 BalusC
 * 
 * This program is free software: you can redistribute it and/or modify it under the terms of the
 * GNU Lesser General Public License as published by the Free Software Foundation, either version 3
 * of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License along with this library.
 * If not, see <http://www.gnu.org/licenses/>.
 * http://balusc.blogspot.com/2008/02/uploading-files-with-jsf.html
 */

import java.io.BufferedReader;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.nio.charset.Charset;

public class Main {
    public static char[] readCharsWithEncoding(File file, Charset charset) throws IOException {
        InputStreamReader isr = new InputStreamReader(new FileInputStream(file), charset);
        BufferedReader br = new BufferedReader(isr);
        char[] chars = new char[(int) file.length()];
        br.read(chars);
        isr.close();
        br.close();
        return chars;
    }

    /**
     * Close the given I/O resource of the given file.
     * @param resource The I/O resource to be closed.
     * @param file The I/O resource's subject.
     */
    private static void close(Closeable resource, File file) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                String message = "Closing file " + file.getPath() + " failed.";
                // Do your thing with the exception and the message. Print it, log it or mail it.
                System.err.println(message);
                e.printStackTrace();
            }
        }
    }
}

Related

  1. readAllLines(Path path, Charset cs)
  2. readAllText(File file, Charset charset)
  3. readAllText(File file, Charset charset)
  4. readAsString(InputStream in, Charset charset)
  5. readAsString(InputStream is, CharsetDecoder decoder)
  6. reader(Class baseClass, String resourceName, Charset charset)
  7. reader(InputStream in, String charsetName)
  8. readerBuffered(final File file, final Charset charset)
  9. readFile(Bundle bundle, String path, Charset cs)