Java BufferedReader Read readFile(String filePath)

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

Description

Method that reads a file and returns the resulting String

License

Open Source License

Parameter

Parameter Description
filePath a parameter

Return

String the content of the file read

Declaration

public static String readFile(String filePath) 

Method Source Code


//package com.java2s;
/*// w ww.  j a  v a 2  s  .  com
 * Copyright (c) 2012 Diamond Light Source Ltd.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {
    /**
     * Method that reads a file and returns the resulting String
     * @param filePath
     * @return String
     *       the content of the file read
     */
    public static String readFile(String filePath) {
        StringBuilder contents = new StringBuilder();

        try {
            // use buffering, reading one line at a time
            // FileReader always assumes default encoding is OK!
            BufferedReader input = new BufferedReader(new FileReader(filePath));
            try {
                String line = null;
                int i = 0;
                while ((line = input.readLine()) != null) {
                    if (i > 0)
                        contents.append(System.getProperty("line.separator"));
                    contents.append(line);
                    i++;
                }

            } finally {
                input.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return contents.toString();
    }
}

Related

  1. readFile(String fileName, String basePath)
  2. readFile(String fileName, String commentFlag)
  3. readFile(String fileName, String commentFlag)
  4. readFile(String fileNm)
  5. readFile(String filePath)
  6. readFile(String filePath)
  7. readFile(String filePath)
  8. readFile(String filePath)
  9. readFile(String filePath)