Java FileReader Read readFileAsArray(String filename)

Here you can find the source of readFileAsArray(String filename)

Description

Reads a file into a string array

License

Open Source License

Parameter

Parameter Description
filename The file name

Exception

Parameter Description
IOException if I/O occurs

Return

The file contents as a string array

Declaration

public static String[] readFileAsArray(String filename) throws IOException 

Method Source Code

//package com.java2s;

import java.io.FileReader;
import java.io.IOException;

import java.io.LineNumberReader;

import java.util.LinkedList;

public class Main {
    /**/* www  .  j a va  2 s.c om*/
     * Reads a file into a string array
     * 
     * @param filename The file name
     * @return The file contents as a string array
     * @throws IOException if I/O occurs
     */
    public static String[] readFileAsArray(String filename) throws IOException {
        LinkedList<String> file = new LinkedList<String>();
        String[] lines = new String[0];
        String line;
        FileReader reader = null;
        LineNumberReader lineReader = null;

        try {
            reader = new FileReader(filename);
            lineReader = new LineNumberReader(reader);

            while ((line = lineReader.readLine()) != null) {
                file.add(line);
            }

            lines = new String[file.size()];
            lines = file.toArray(lines);
        } finally {
            try {
                lineReader.close();
                reader.close();
            } catch (Exception e) {
                // Do nothing
            }
        }

        return lines;
    }
}

Related

  1. readFile(String fileName)
  2. readFile(String filename)
  3. readFile(String filename)
  4. readFile(String fileName)
  5. readFile(String fileName, StringBuffer buffer)
  6. readFileOrThrow(File file)