Java File Read by Charset toString(File file, String charset)

Here you can find the source of toString(File file, String charset)

Description

to String

License

Apache License

Declaration

public static String toString(File file, String charset) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.File;

import java.io.IOException;

import java.io.RandomAccessFile;

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
    public static String toString(File file, String charset) throws IOException {
        ByteBuffer buf = read(file, 0, (int) file.length());
        return new String(buf.array(), buf.arrayOffset(), buf.remaining(), charset);
    }// ww w .ja  v  a2  s  .  c  o m

    public static ByteBuffer read(File file, long offset, int length) throws IOException {
        FileChannel chan = channel(file, false);

        ByteBuffer buf = ByteBuffer.allocate(length);
        chan.position(offset);

        while (buf.remaining() > 0) {
            if (chan.read(buf) <= 0) {
                throw new IOException("Failed to read from channel.");
            }
        }

        buf.rewind();
        chan.close();

        return buf;
    }

    public static FileChannel channel(File file, boolean writeable) throws IOException {
        String opts = writeable ? "rw" : "r";
        RandomAccessFile fd = new RandomAccessFile(file, opts);
        FileChannel chan = fd.getChannel();

        return chan;
    }
}

Related

  1. setPropertiesVaule(File file, String key, String value, String comments, Charset charset)
  2. setText(File file, Charset charset, String text)
  3. stringToFile(final String s, final File f, final Charset c)
  4. stringToFile(final String string, final Path path, final Charset charset)
  5. toFiles(@Nonnull Process p, @Nonnull Charset charset)
  6. toString(final Path filePath, final Charset encoding)
  7. utf8Decoder(CodingErrorAction codingErrorAction, Charset fileCharset)