Java Path File Name nio readFileFromPath(String filename)

Here you can find the source of readFileFromPath(String filename)

Description

Returns file content as string, reading from a path.

License

Apache License

Parameter

Parameter Description
filename the path to the file to read.

Return

File content as string.

Declaration

public static String readFileFromPath(String filename) 

Method Source Code


//package com.java2s;
/*/*from w w  w . ja  v  a  2  s .  com*/
 * 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.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

import java.nio.charset.Charset;
import com.google.common.io.Files;

public class Main {
    /**
     * Returns file content as string, reading from a path. 
     * Throws runtime exception in case of FileNotFoundException or IOException.
     * 
     * @param filename the path to the file to read.
     * @return File content as string.
     */
    public static String readFileFromPath(String filename) {
        return readFileFromPath(filename, null);
    }

    /**
     * 
     * @param filename
     * @param encoding the encoding to use, null means platform default
     * @return the given file content
     */
    public static String readFileFromPath(String filename, String encoding) {
        try {
            Charset charset = charsetForNameOrDefault(encoding);
            return Files.toString(new File(filename), charset);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static Charset charsetForNameOrDefault(String encoding) {
        Charset charset = (encoding == null) ? Charset.defaultCharset() : Charset.forName(encoding);
        return charset;
    }
}

Related

  1. isHiddenName(Path path)
  2. jobNameFromPath(Path path)
  3. listDocTypeName(Path path)
  4. makeUnique(Path basePath, String baseName)
  5. pathToPackageName(Path path)
  6. relativizePath(Path relativeTo, String filename)
  7. rename(Path origin, Path destination)
  8. renameFile(Path filePath, String postfix)
  9. renameLogFile(Path original)