Java Scanner Read All readTextFile(String path)

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

Description

Read the text file by one whole line and add each line to a String list.

License

Open Source License

Parameter

Parameter Description
path a parameter

Exception

Parameter Description
FileNotFoundException an exception

Declaration

public static List<String> readTextFile(String path) throws FileNotFoundException 

Method Source Code


//package com.java2s;

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

import java.util.ArrayList;

import java.util.List;
import java.util.Scanner;

public class Main {
    /**//  w w  w  . j a  v  a2 s.  c  o  m
     * Read the text file by one whole line and add each line to a String list.
     * 
     * @param path
     * @return
     * @throws FileNotFoundException
     */
    public static List<String> readTextFile(String path) throws FileNotFoundException {
        List<String> wordList = new ArrayList<String>();
        Scanner input = null;
        try {
            input = new Scanner(new FileInputStream(new File(path)), "UTF-8");
            while (input.hasNext()) {
                String text = input.nextLine().trim();
                if (text.startsWith("#")) // skip comment
                    continue;
                if (!text.equals(""))
                    wordList.add(text);
            }
        } finally {
            if (input != null)
                input.close();
        }
        return wordList;
    }
}

Related

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