Java BufferedReader Read readFile(final String name)

Here you can find the source of readFile(final String name)

Description

Reads the contents of a file.

License

Open Source License

Parameter

Parameter Description
name the name of the file to read

Return

the contents of the file if successful, an empty string otherwise.

Declaration

public static String readFile(final String name) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    /**// ww w.j a v a2 s .  co m
     * Reads the contents of a file.
     * 
     * @param name
     *            the name of the file to read
     * @return the contents of the file if successful, an empty string
     *         otherwise.
     */
    public static String readFile(final String name) {
        FileReader fileReader = null;
        final StringBuilder contents = new StringBuilder();
        try {
            final File file = new File(name);
            if (!file.exists()) {
                throw new IllegalArgumentException("File " + name + " does not exist");
            }
            fileReader = new FileReader(file);
            final BufferedReader reader = new BufferedReader(fileReader);
            String inputLine = reader.readLine();
            while (inputLine != null) {
                contents.append(inputLine).append("\n");
                inputLine = reader.readLine();
            }
            reader.close();
        } catch (final IOException i1) {
            throw new RuntimeException(i1);
        }
        return contents.toString();
    }
}

Related

  1. readFile(final String file)
  2. readFile(final String fileName)
  3. readFile(final String filename)
  4. readFile(final String fileName)
  5. readFile(final String filePath)
  6. readFile(final String path)
  7. readFile(final String pFile)
  8. readFile(List fieldNames, String filename)
  9. readFile(Reader reader)