read List of String From File - Java java.util

Java examples for java.util:List Creation

Description

read List of String From File

Demo Code


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class Main {

  public static List<String> readListFromFile(String filePath) throws IOException {
    List<String> result = new ArrayList<String>();

    InputStream fis = null;//from w w  w.java2 s  .  c  om
    BufferedReader br = null;

    try {
      fis = new FileInputStream(filePath);
      br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
      String line;
      while ((line = br.readLine()) != null) {
        String trimmed = line.trim();
        if (!trimmed.isEmpty()) {
          result.add(line);
        }
      }
    } finally {
      if (br != null) {
        br.close();
      }
      if (fis != null) {
        fis.close();
      }
    }

    return result;

  }
}

Related Tutorials