Java FileReader Read All readAllLines(String filePath)

Here you can find the source of readAllLines(String filePath)

Description

Reads the contents of the specified file

License

Open Source License

Parameter

Parameter Description
filePath - The path of the file to read from

Exception

Parameter Description
IOException If there's an error while reading from the file

Return

A string array with the contents of the read file

Declaration

public static String[] readAllLines(String filePath) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2012 MCForge - Modified for use with Chatterbox
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html//  w w w  .j  av a  2 s  . co m
 ******************************************************************************/

import java.io.FileReader;

import java.io.IOException;
import java.io.LineNumberReader;

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**
     * Reads the contents of the specified file
     * 
     * @param filePath
     *            - The path of the file to read from
     * 
     * @return A string array with the contents of the read file
     * @throws IOException
     *             If there's an error while reading from the file
     */
    public static String[] readAllLines(String filePath) throws IOException {
        List<String> lines = fileToStringList(filePath);
        return lines.toArray(new String[lines.size()]);
    }

    /**
     * Reads the contents of the specified file
     * 
     * @param filePath
     *            - The path of the file to read from
     * 
     * @return A string list with the contents of the read file
     * @throws IOException
     *             If there's an error while reading from the file
     */
    public static List<String> fileToStringList(String filePath) throws IOException {
        LineNumberReader reader = new LineNumberReader(new FileReader(filePath));
        List<String> lines = new ArrayList<String>();
        String line;
        while ((line = reader.readLine()) != null)
            lines.add(line);
        reader.close();
        return lines;
    }
}

Related

  1. readAll(File file)
  2. readAll(String path)
  3. readAllKeys(String propertyFileName, String xmlFileName)