Java Text File Read by Charset readLines(String filePath, Charset charset)

Here you can find the source of readLines(String filePath, Charset charset)

Description

read Lines

License

Open Source License

Exception

Parameter Description
IOException an exception

Return

a list of lines in the given file. Lines which begin with # are considered to be commented out and are ignored. Empty lines are also ignored.

Declaration

static List<String> readLines(String filePath, Charset charset) throws IOException 

Method Source Code


//package com.java2s;
/*/*  www .j  a va  2 s.c o  m*/
 * ----------------------------------------------------------------------------
 * "THE WINE-WARE LICENSE" Version 1.0:
 * Authors: Carmen Alvarez. 
 * As long as you retain this notice you can do whatever you want with this stuff. 
 * If we meet some day, and you think this stuff is worth it, you can buy me a 
 * glass of wine in return. 
 * 
 * THE AUTHORS OF THIS FILE ARE NOT RESPONSIBLE FOR LOSS OF LIFE, LIMBS, SELF-ESTEEM,
 * MONEY, RELATIONSHIPS, OR GENERAL MENTAL OR PHYSICAL HEALTH CAUSED BY THE
 * CONTENTS OF THIS FILE OR ANYTHING ELSE.
 * ----------------------------------------------------------------------------
 */

import java.io.BufferedReader;

import java.io.FileInputStream;
import java.io.IOException;

import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class Main {
    /**
     * @return a list of lines in the given file. Lines which begin with # are considered to be commented out and are ignored.
     *         Empty lines are also ignored.
     * @throws IOException
     */
    static List<String> readLines(String filePath, Charset charset) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), charset));
        List<String> result = new ArrayList<String>();
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            // remove comments
            line = line.replaceAll("#.*$", "");
            line = line.trim();
            if (line.isEmpty())
                continue;
            result.add(line);
        }
        reader.close();
        return result;
    }
}

Related

  1. readInputStreamToString(InputStream instream, Charset charset)
  2. readLineFromStream(InputStream is, StringBuffer buffer, CharsetDecoder decoder)
  3. readLines(InputStream in, Charset cs)
  4. readLines(InputStream input, Charset charset)
  5. readLines(InputStream is, CharsetDecoder decoder)
  6. readLines(String path, Charset charset)
  7. readNextWord(BufferedInputStream in, Charset cs)
  8. readStreamAsString(final InputStream iStream, Charset iCharset)
  9. readStreamToString(InputStream stream, Charset encoding)