Java File to String fileToString(String filename)

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

Description

Convert the content of the given file to string.

License

Open Source License

Parameter

Parameter Description
filename the file to read.

Exception

Parameter Description
Exception any exception occurs.

Return

the content of the file.

Declaration

public static String fileToString(String filename) throws Exception 

Method Source Code

//package com.java2s;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class Main {
    /**/*from   w  ww  .  j  a  v  a  2 s.c o m*/
     * <p>
     * Convert the content of the given file to string.
     * </p>
     * @param filename the file to read.
     * @return the content of the file.
     * @throws Exception any exception occurs.
     */
    public static String fileToString(String filename) throws Exception {
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new InputStreamReader(
                    new FileInputStream(new File(filename))));

            StringBuffer sb = new StringBuffer();

            // Buffer for reading.
            char[] buffer = new char[1024];
            int k = 0;

            // Read characters and append to string buffer
            while ((k = reader.read(buffer)) != -1) {
                sb.append(buffer, 0, k);
            }

            return sb.toString();
        } finally {
            reader.close();
        }
    }
}

Related

  1. fileToString(String filename)
  2. fileToString(String fileName)
  3. fileToString(String fileName)
  4. fileToString(String fileName)
  5. fileToString(String filename)
  6. fileToString(String fileName)
  7. fileToString(String fileName)
  8. fileToString(String filename)
  9. fileToString(String fileName)