Java File to String fileToString(String fileName)

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

Description

read the file content as a String with default character encoding.

License

Apache License

Parameter

Parameter Description
fileName a parameter

Declaration

public static String fileToString(String fileName) 

Method Source Code


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

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Main {
    /**/*from  w  w  w. ja v  a2  s.c o m*/
     * read the file content as a String with default character encoding.
     * 
     * @param fileName
     * @return
     */
    public static String fileToString(String fileName) {
        StringBuffer stringBuffer = new StringBuffer();

        try {
            char[] buffer = new char[1024];
            FileReader reader = new FileReader(fileName);
            int flag = -1;
            while ((flag = reader.read(buffer, 0, buffer.length)) != -1) {
                stringBuffer.append(buffer, 0, flag);
            }
        } catch (FileNotFoundException e) {
            throw new IllegalArgumentException("[" + fileName + "] is not found.");
        } catch (IOException e) {
            throw new RuntimeException("Unexpected exception! caused by: " + e.getMessage(), e);
        }

        return stringBuffer.toString();
    }
}

Related

  1. fileToString(String file)
  2. fileToString(String file, String encoding)
  3. FileToString(String file_name)
  4. fileToString(String filename)
  5. fileToString(String filename)
  6. fileToString(String fileName)
  7. fileToString(String fileName)
  8. fileToString(String filename)
  9. fileToString(String filename)