Java FileReader Create readTextFile(String filename)

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

Description

Reads the contents of the given file.

License

Open Source License

Parameter

Parameter Description
filename The name of the given file.

Exception

Parameter Description
FileNotFoundException an exception
IOException an exception

Return

The file's contents.

Declaration

public static String readTextFile(String filename)
        throws FileNotFoundException, IOException 

Method Source Code

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

import java.io.BufferedReader;
import java.io.File;

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

public class Main {
    /**//w  ww . j  ava 2 s. c o  m
     * Reads the contents of the given file.
     * @param filename The name of the given file.
     * @return The file's contents.
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String readTextFile(String filename)
            throws FileNotFoundException, IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(
                new File(filename)))) {
            String line = reader.readLine();
            while (line != null) {
                sb.append(line);
                line = reader.readLine();
                if (line != null) {
                    sb.append("\n");
                }
            }
        }
        String text = sb.toString();
        return text;
    }
}

Related

  1. readTextFile(String filename)
  2. readTextFile(String fileName)
  3. readTextFile(String fileName)
  4. readTextFile(String fileName)
  5. readTextFile(String fileName)
  6. readTextFile(String filename)
  7. readTextFile(String fileName, boolean newline)
  8. readTextFile(String fileName, String enc)
  9. readTextFile(String filePath)