Java Text File Read by Encode getFileContentAsString(String filePath, String fileEncoding)

Here you can find the source of getFileContentAsString(String filePath, String fileEncoding)

Description

get File Content As String

License

Apache License

Declaration

public static String getFileContentAsString(String filePath, String fileEncoding)
            throws FileNotFoundException, IOException 

Method Source Code


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

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

public class Main {
    private static final String DEFAULT_ENCODING = "UTF-8";

    public static String getFileContentAsString(String filePath, String fileEncoding)
            throws FileNotFoundException, IOException {
        StringBuilder text = new StringBuilder();
        String newLine = System.getProperty("line.separator");
        try (Scanner scanner = new Scanner(new FileInputStream(filePath), fileEncoding)) {
            boolean isFirstLine = true;
            while (scanner.hasNextLine()) {
                if (isFirstLine) {
                    text.append(scanner.nextLine());
                    isFirstLine = false;
                } else {
                    text.append(newLine).append(scanner.nextLine());
                }//from  w w w  .j a  v  a2s  .  c  o m
            }
        }
        return text.toString();
    }

    public static String getFileContentAsString(String filePath) throws FileNotFoundException, IOException {
        return getFileContentAsString(filePath, DEFAULT_ENCODING);
    }
}

Related

  1. getFileContent(FileInputStream fis, String encoding)
  2. getFileContent(InputStream is, String encoding)
  3. getFileContentAsString(File file, String encoding)
  4. getFileContentAsString(File file, String encoding)
  5. getFileContentAsString(File file, String encoding)
  6. getFileContents(InputStream stream, String encoding)
  7. getFileContents(String filename, String encoding)
  8. readFileAsString(final File f, final String encoding)
  9. readFileAsString(InputStream input, OutputStream output, String inputEncoding)