Java BufferedReader Read readFile(File file)

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

Description

read File

License

Open Source License

Parameter

Parameter Description
file The file to read

Exception

Parameter Description
IOException an exception

Return

The content of the file as String

Declaration

public static String readFile(File file) throws IOException 

Method Source Code


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

import java.io.*;
import java.util.Objects;

public class Main {
    /**/* ww  w  .j av  a 2 s  .  c om*/
     *
     * @param fileName    Name of the file, MUST be in data folder
     * @return The content of the file as String
     * @throws IOException
     */
    public static String readFile(String fileName) throws IOException {
        Objects.requireNonNull(fileName);
        if (fileName.isEmpty()) {
            throw new IOException("fileName cannot be empty.");
        }

        return readFile(new File(getOutputFolder() + fileName));
    }

    /**
     *
     * @param file    The file to read
     * @return The content of the file as String
     * @throws IOException
     */
    public static String readFile(File file) throws IOException {
        Objects.requireNonNull(file);
        if (file.isDirectory()) {
            throw new IOException("This is a directory not a file.");
        }

        if (!file.exists()) {
            throw new IOException("Given file " + file.getName() + " doesn't exist.");
        }

        StringBuilder fileContentBuilder = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            for (String line = br.readLine(); line != null; line = br.readLine()) {
                if (!line.isEmpty()) {
                    fileContentBuilder.append(line).append("\n");
                }
            }
        }

        return fileContentBuilder.toString();
    }

    public static String getOutputFolder() {
        return System.getProperty("user.dir") + "/data/";
    }
}

Related

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