Java File Content Read getFileContents(final File f)

Here you can find the source of getFileContents(final File f)

Description

get File Contents

License

Open Source License

Declaration

public static String getFileContents(final File f) throws IOException 

Method Source Code


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

import java.io.File;
import java.io.IOException;

import java.util.NoSuchElementException;

import java.util.Scanner;

public class Main {
    private static final String DEFAULT_ENCODING = "UTF-8";

    public static String getFileContents(final File f) throws IOException {
        return getFileContents(f, DEFAULT_ENCODING);
    }//  ww w .  ja v a 2s  .  co m

    public static String getFileContents(final File f, final String enc) throws IOException {
        String content;
        try (Scanner scanner = new Scanner(f, enc).useDelimiter("\\Z")) {
            content = getScannerContents(scanner);
        } catch (NoSuchElementException | IllegalStateException e) {
            throw e;
        }
        return content;
    }

    public static String getScannerContents(final Scanner scanner) throws IllegalArgumentException {
        String content;
        if (scanner.hasNext()) { // will be false if file size == 0
            content = scanner.next();
        } else {
            content = "";
        }
        return content;
    }
}

Related

  1. getFileContents(File f)
  2. getFileContents(File file)
  3. getFileContents(File file)
  4. getFileContents(File methodPatch)
  5. getFileContents(File testFile)
  6. getFileContents(final File file)
  7. getFileContents(String filename)
  8. getFileContents(String fileName)