Java File to String fileToString(String filePath, String encoding)

Here you can find the source of fileToString(String filePath, String encoding)

Description

file To String

License

Apache License

Declaration

public static String fileToString(String filePath, String encoding) 

Method Source Code

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

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStreamReader;

import java.io.StringWriter;

public class Main {

    public static String fileToString(String filePath, String encoding) {
        InputStreamReader reader = null;
        StringWriter writer = new StringWriter();
        try {//www .j ava  2s  .  co  m
            if (encoding == null || "".equals(encoding)) {
                reader = new InputStreamReader(new FileInputStream(new File(filePath)), encoding);
            } else {
                reader = new InputStreamReader(new FileInputStream(new File(filePath)));
            }
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = reader.read(buffer))) {
                writer.write(buffer, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }

            }
        }
        if (writer != null) {
            return writer.toString();
        } else {
            return null;
        }
    }
}

Related

  1. fileToString(String fileName)
  2. fileToString(String fileName)
  3. fileToString(String fileName)
  4. fileToString(String fileName, String timestamp, String adapterName)
  5. fileToString(String filePath)
  6. fileToString(String nomeArquivo)
  7. fileToString(String path)
  8. fileToString(String pathname)
  9. fileToString(String strPath)