Java Scanner Read All readTextFileAsString(File textFile)

Here you can find the source of readTextFileAsString(File textFile)

Description

Read the entire given file and return the contents as one long String.

License

Open Source License

Parameter

Parameter Description
textFile a parameter

Exception

Parameter Description
FileNotFoundException an exception

Declaration

public static String readTextFileAsString(File textFile) throws FileNotFoundException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010 - 2013 Danny Katzel.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html/*from w ww  . j a  va  2  s  .c  o  m*/
 * 
 * Contributors:
 *     Danny Katzel - initial API and implementation
 ******************************************************************************/

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

import java.util.Scanner;

public class Main {
    /**
     * Read the entire given file and return the contents
     * as one long String.  This should only be used for small
     * text files and is not intended to be used on large files
     * or files that are not text only.
     * @param textFile
     * @return
     * @throws FileNotFoundException
     */
    public static String readTextFileAsString(File textFile) throws FileNotFoundException {
        StringBuilder outputText = new StringBuilder();
        Scanner scanner = new Scanner(textFile);
        while (scanner.hasNextLine()) {
            outputText.append(scanner.nextLine()).append(String.format("%n"));
        }
        scanner.close();
        String actualText = outputText.toString();
        return actualText;
    }
}

Related

  1. readTextFile(File file)
  2. readTextFile(File file)
  3. readTextFile(String filename)
  4. readTextFile(String path)
  5. readTextFile(String path)