Android Binary File Read readFile(File f)

Here you can find the source of readFile(File f)

Description

Reads the contents of a text file and returns them in a string

License

Open Source License

Parameter

Parameter Description
f The text file to read

Exception

Parameter Description
IOException an exception

Return

The contents of the file as a string

Declaration

public static String readFile(File f) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2012 BragiSoft, Inc.//from   ww w.  j  av a  2  s. c  o m
 * This source is subject to the BragiSoft Permissive License.
 * Please see the License.txt file for more information.
 * All other rights reserved.
 * 
 * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
 * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
 * PARTICULAR PURPOSE.
 * 
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Contributors:
 * Jan-Christoph Klie - Everything
 * 
 *******************************************************************************/

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

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

public class Main {
    /**
     * Reads the contents of a text file and returns them in a string 
     * @param f The text file to read
     * @return The contents of the file as a string
     * @throws IOException
     */
    public static String readFile(File f) throws IOException {
        FileInputStream stream = new FileInputStream(f);
        try {
            FileChannel fc = stream.getChannel();
            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(File file)
  2. read(String fileName)
  3. readFile(File file)
  4. readFile(File file, int size)
  5. readResource(String resourceName)