Java File Read via ByteBuffer readStringFromFile(String path)

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

Description

Reads entire contents of specified file as a string.

License

Open Source License

Parameter

Parameter Description
path file path to read

Exception

Parameter Description
IOException an exception

Return

string read from specified file

Declaration

public static String readStringFromFile(String path) throws IOException 

Method Source Code

//package com.java2s;
/**//from w ww .  j  av  a 2  s.  c o m
 * Copyright 2016 LinkedIn Corp. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.charset.Charset;

public class Main {
    /**
     * Reads entire contents of specified file as a string.
     *
     * @param path file path to read
     * @return string read from specified file
     * @throws IOException
     */
    public static String readStringFromFile(String path) throws IOException {
        File file = new File(path);
        byte[] encoded = new byte[(int) file.length()];
        DataInputStream ds = null;
        try {
            ds = new DataInputStream(new FileInputStream(file));
            ds.readFully(encoded);
        } finally {
            if (ds != null) {
                ds.close();
            }
        }
        return Charset.defaultCharset().decode(ByteBuffer.wrap(encoded)).toString();
    }
}

Related

  1. readShort(DataInput input)
  2. readShortBuffer(DataInputStream input)
  3. readShortByteArray(DataInput in)
  4. readString(ByteArrayInputStream bin)
  5. readString(ReadableByteChannel channel)
  6. readStringFromSocketChannel(SocketChannel sc)
  7. readStringInUTF8(DataInput in)
  8. readToBuffer(final String filename)
  9. readToByteArray(String fname)