Java Text File Read by Charset readFileContents(File file, Charset charset)

Here you can find the source of readFileContents(File file, Charset charset)

Description

read File Contents

License

Open Source License

Declaration

public static String readFileContents(File file, Charset charset) throws Exception 

Method Source Code


//package com.java2s;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

import java.nio.file.Files;
import java.nio.file.Paths;

public class Main {
    public static String readFileContents(File file) throws Exception {
        return readFileContents(file, Charset.forName("UTF-8"));
    }/* w ww .ja v a  2 s.  com*/

    public static String readFileContents(File file, Charset charset) throws Exception {
        BufferedReader br = null;
        StringBuilder sb = null;
        String line;
        if (file != null && charset != null) {
            if (file.exists()) {
                try {
                    sb = new StringBuilder();
                    br = Files.newBufferedReader(Paths.get(file.getPath()), charset);
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }
                    br.close();
                    return sb.toString();
                } catch (IOException ex) {
                    throw ex;
                }
            }
            throw new Exception("The file does not exist.");
        }
        throw new Exception("Invalid or incomplete parameters.");
    }
}

Related

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