Java FileReader Create readTextFile(File file)

Here you can find the source of readTextFile(File file)

Description

Reads the content of a text file.

License

Apache License

Parameter

Parameter Description
file The file.

Exception

Parameter Description
IOException If the file could not be read.

Return

The content.

Declaration

public static String readTextFile(File file) throws IOException 

Method Source Code


//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.io.BufferedReader;

import java.io.File;
import java.io.FileReader;

import java.io.IOException;

public class Main {
    /** Platform specific NEWLINE character. */
    private static final String NEWLINE = System.getProperty("line.separator");

    /**/*from w ww  . j a v a2s . co m*/
     * Reads the content of a text file.
     * 
     * @param file
     *            The file.
     * @return The content.
     * 
     * @throws IOException
     *             If the file could not be read.
     */
    public static String readTextFile(File file) throws IOException {
        if (!file.isFile()) {
            throw new IllegalArgumentException("File not found: " + file.getAbsolutePath());
        }
        if (!file.canRead()) {
            throw new IllegalArgumentException("File not readable: " + file.getAbsolutePath());
        }

        String content = null;
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line).append(NEWLINE);
            }
            content = sb.toString();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    // Best effort; ignore.
                }
            }
        }
        return content;
    }
}

Related

  1. readTextFile(File file)
  2. readTextFile(File file)
  3. readTextFile(File file)
  4. readTextFile(File file)
  5. readTextFile(File file)
  6. readTextFile(File file)
  7. readTextFile(File file)
  8. readTextFile(File file)
  9. readTextFile(File file)