Java Text File Read Line readLines(File file, String charsetName)

Here you can find the source of readLines(File file, String charsetName)

Description

read Lines

License

Open Source License

Declaration

public static List<String> readLines(File file, String charsetName) 

Method Source Code


//package com.java2s;
/*//  w  w  w  .j  a va 2s . co m
 * Copyright (c) 2014 Eike Stepper (Berlin, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Eike Stepper - initial API and implementation
 */

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static List<String> readLines(File file, String charsetName) {
        List<String> lines = new ArrayList<String>();

        if (file.exists()) {
            InputStream in = null;
            Reader reader = null;
            BufferedReader bufferedReader = null;

            try {
                in = new FileInputStream(file);
                reader = charsetName == null ? new InputStreamReader(in) : new InputStreamReader(in, charsetName);
                bufferedReader = new BufferedReader(reader);

                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    lines.add(line);
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            } finally {
                close(bufferedReader);
                close(reader);
                close(in);
            }
        }

        return lines;
    }

    public static void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Related

  1. readLines(File file)
  2. readLines(File file)
  3. readLines(File file, boolean ignoreComments)
  4. readLines(File file, int maxArraySize)
  5. readLines(File file, String charset)
  6. readLines(File file, String encoding)
  7. readLines(File file, String encoding)
  8. readLines(File file, String outputLineEnding)
  9. readLines(File inputFile)