Java Convert via ByteBuffer toString(final String filename)

Here you can find the source of toString(final String filename)

Description

Converts the contents of a file to a String

License

LGPL

Parameter

Parameter Description
filename - The name of the file to get as a string

Exception

Parameter Description
IOException If an IO error occurs

Return

String with the contents of the file, null if the file does not exist

Declaration

public static String toString(final String filename) throws IOException 

Method Source Code

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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;

import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class Main {
    /**/* w  w w .  jav a 2 s .c o m*/
     * Converts the contents of a file to a String
     * 
     * @param filename
     *            - The name of the file to get as a string
     * @return String with the contents of the file, null if the file does not
     *         exist
     * @throws IOException
     *             If an IO error occurs
     */
    public static String toString(final String filename) throws IOException {
        return toString(new File(filename));
    }

    /**
     * Converts the contents of a file to a String
     * 
     * @param file
     *            - The file to get as a string
     * @return String with the contents of the file, null if the file does not
     *         exist
     * @throws IOException
     *             If an IO error occurs
     */
    public static String toString(final File file) throws IOException {
        if (file.exists()) {
            FileInputStream stream = null;
            try {
                stream = new FileInputStream(file);
            } catch (final FileNotFoundException e) {
            }

            final FileChannel fc = stream.getChannel();
            final MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());

            final String content = Charset.defaultCharset().decode(bb).toString();

            stream.close();

            return content;
        }
        return null;
    }
}

Related

  1. toShortArray(byte[] arr)
  2. toShortArray(final byte[] byteArray)
  3. toSimpleList(List attrValues)
  4. toString(byte[] buf, int arrayOffset, int origLimit, StringBuilder sb)
  5. toString(byte[] value, int offset, int length, String encoding)
  6. toString(final Xid xid)
  7. toString(InputStream is)
  8. toString(Object o)
  9. toString(Reader r)