Java File Read via ByteBuffer read(final File source)

Here you can find the source of read(final File source)

Description

read

License

Apache License

Exception

Parameter Description
IOException if there is a file-system error.

Return

Content of the file as a string.

Declaration

public static String read(final File source) throws IOException 

Method Source Code


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

import java.io.*;
import java.net.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class Main {
    /**/* w  ww  .jav a  2  s . com*/
     * Read the content of a URL to a string.
     *
     * @throws IOException
     */
    public static String read(final URL source) throws IOException {
        final BufferedReader in = new BufferedReader(new InputStreamReader(source.openStream()));
        final StringBuilder response = new StringBuilder(5000);
        String line;

        while ((line = in.readLine()) != null) {
            response.append(line);
        }

        in.close();

        return response.toString();
    }

    /**
     * @link http://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file
     *
     * @return Content of the file as a string.
     * @throws IOException if there is a file-system error.
     */
    public static String read(final File source) throws IOException {
        final FileInputStream stream = new FileInputStream(source);
        try {
            final FileChannel fc = stream.getChannel();
            final MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());

            // Instead of using default, pass in a decoder.
            return Charset.defaultCharset().decode(bb).toString();
        } finally {
            stream.close();
        }
    }
}

Related

  1. read(DataInput in, int length)
  2. read(File file)
  3. read(File file)
  4. read(File file, long offset, int length)
  5. read(File from)
  6. read(final FileChannel channel)
  7. read(final Reader input, final char[] buffer, final int offset, final int length)
  8. read(InputStream stream)
  9. read(Path file)