Java Scanner Read readFile(File f)

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

Description

Read the given file with UTF-8 encoding into a string and return it.

License

Open Source License

Parameter

Parameter Description
f the file to be read

Exception

Parameter Description
IOException an exception

Return

the contents as text

Declaration

public static String readFile(File f) throws FileNotFoundException, IOException 

Method Source Code

//package com.java2s;
/*  MonkeyTalk - a cross-platform functional testing tool
Copyright (C) 2012 Gorilla Logic, Inc./*from   w ww  .  j  a v a2  s.co m*/
    
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.
    
You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>. */

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.Scanner;

public class Main {
    /**
     * Read the given file with UTF-8 encoding into a string and return it.
     * 
     * @param f
     *            the file to be read
     * @return the contents as text
     * @throws IOException
     */
    public static String readFile(File f) throws FileNotFoundException, IOException {
        StringBuilder sb = new StringBuilder();
        Scanner scanner = new Scanner(new FileInputStream(f), "UTF-8");
        try {
            while (scanner.hasNextLine()) {
                sb.append(scanner.nextLine()).append('\n');
            }
        } finally {
            scanner.close();
        }
        return (sb.length() > 0 ? sb.substring(0, sb.length() - 1) : "");
    }
}

Related

  1. read()
  2. read(Class clazz, String f)
  3. readArr(Scanner in, int n)
  4. readCQLFile(String cqlFileName)
  5. readFile(Class ownerClass, String fileName)
  6. readFile(File f)
  7. readFile(File f)
  8. readFile(File file)
  9. readFile(File file)