Java Scanner Read All readTextFile(String filename)

Here you can find the source of readTextFile(String filename)

Description

read Text File

License

LGPL

Declaration

public static String readTextFile(String filename) 

Method Source Code


//package com.java2s;
//License from project: LGPL 

import java.io.File;

import java.io.IOException;

import java.util.Scanner;

public class Main {
    public static String readTextFile(String filename) {
        return readTextFile(new File(filename));
    }//w ww . j  av a2  s  .c  om

    public static String readTextFile(File file) {
        try {
            Scanner scan = new Scanner(file);

            String s = "";

            while (scan.hasNextLine()) {
                s += scan.nextLine() + "\n";
            }

            if (s.length() > 0)
                s = s.substring(0, s.length() - 1);

            scan.close();
            return s;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Reading of file " + file.getName() + " failed! Returning empty string...");
            return "";
        }
    }
}

Related

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