Java File Read via ByteBuffer readFile(String path)

Here you can find the source of readFile(String path)

Description

Read File into a String.

License

Open Source License

Parameter

Parameter Description
path the path

Exception

Parameter Description
IOException Signals that an I/O exception has occurred.

Return

the string

Declaration

public static String readFile(String path) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2017 Red Hat, Inc and others.
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * SPDX-License-Identifier: EPL-2.0// w w w  . j  a  v a2  s  .  c  o  m
 *
 * Contributors:
 *     Red Hat, Inc - initial API and implementation
 *******************************************************************************/

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 {
    /**
     * Read File into a String.
     *
     * @param path the path
     * @return the string
     * @throws IOException Signals that an I/O exception has occurred.
     */
    public static String readFile(String path) throws IOException {
        FileInputStream stream = new FileInputStream(new File(path));
        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. readFile(String filePath)
  2. readFile(String name)
  3. readFile(String name)
  4. readFile(String path)
  5. readFile(String path)
  6. readFile(String path)
  7. readFileAsByteArray(File file)
  8. readFileAsByteArray(String path)
  9. readFileAsStringArray(File file)