Java Text File Read by Charset readFile(String path, Charset charset)

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

Description

read File

License

Apache License

Declaration

public static String readFile(String path, Charset charset) throws IOException 

Method Source Code

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

import java.io.File;

import java.io.IOException;

import java.nio.charset.Charset;
import java.nio.file.Files;

import java.util.List;

public class Main {
    public static final String STR_EMPTY = "";
    public static final String STR_NEWLINE = System.getProperty("line.separator");
    private static final String UTF8_BOM = "\uFEFF";

    public static String readFile(String path) throws IOException {
        return readFile(path, Charset.forName("UTF-8"));
    }/*from w  w  w  . jav a 2 s. co  m*/

    public static String readFile(String path, Charset charset) throws IOException {
        StringBuilder content = new StringBuilder();
        List<String> allLines = Files.readAllLines(new File(path).toPath(), charset);
        for (String someLine : allLines) {
            content.append(someLine);
            content.append(STR_NEWLINE);
        }
        return content.toString().replaceFirst(UTF8_BOM, STR_EMPTY);
    }

    public static String toString(Object stringObject) {
        return toString(stringObject, "");
    }

    public static String toString(Object stringObject, String value2) {
        if (stringObject != null) {
            return stringObject.toString();
        } else {
            return value2;
        }
    }
}

Related

  1. readFile(File file, Charset charset)
  2. readFile(File file, Charset cs)
  3. readFile(File file, String charsetName)
  4. readFile(File theFile, Charset theCharset)
  5. readFile(final InputStream is, final Charset encoding)
  6. readFile(String path, Charset encoding)
  7. readFileAsString(String path, String charsetName)
  8. readFileContents(File file, Charset charset)
  9. readFileToLines(String inFile, String inCharset)