Java File to String readFileAsString(String filePath)

Here you can find the source of readFileAsString(String filePath)

Description

Read a file content to a string variable

License

Open Source License

Parameter

Parameter Description
filePath The path of the file

Exception

Parameter Description
IOException an exception

Return

The file's content

Declaration

public static String readFileAsString(String filePath) throws IOException 

Method Source Code

//package com.java2s;
/**/* w w  w  .j  av a  2  s.  com*/
  * Copyright (c) 2009 University of Rochester
  *
  * This program is free software; you can redistribute it and/or modify it under the terms of the MIT/X11 license. The text of the  
  * license can be found at http://www.opensource.org/licenses/mit-license.php and copy of the license can be found on the project
  * website http://www.extensiblecatalog.org/. 
  *
  */

import java.io.BufferedInputStream;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;

public class Main {
    private static final int BUFFER_SIZE = 1024;

    /** 
     * Read a file content to a string variable
     * @param filePath The path of the file
     * @return The file's content
     * @throws IOException
     */
    public static String readFileAsString(File filePath) throws IOException {
        return readFileAsString(filePath.getAbsolutePath());
    }

    /**
     * Read a file content to a string variable
     * @param filePath The path of the file
     * @return The file's content
     * @throws IOException
     */
    public static String readFileAsString(String filePath) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream is = new BufferedInputStream(new FileInputStream(filePath));
        byte[] buf = new byte[BUFFER_SIZE];
        int numOfBytes = is.read(buf);
        while (numOfBytes != -1) {
            baos.write(buf, 0, numOfBytes);
            numOfBytes = is.read(buf);
        }
        is.close();
        return new String(baos.toByteArray(), "UTF-8");
    }
}

Related

  1. fileToStringArray(String fileName)
  2. fileToStringBuffer(File file)
  3. fileToStringList(File f)
  4. fileToStringList(String filePath)
  5. fileToStringOneLine(String path)
  6. readFileAsString(String filePath)
  7. readFileAsString(String filePath)
  8. readFileAsString(String filePath)
  9. readFileAsString(String filePath)