Java File to Text Line fileToLines(String fileName)

Here you can find the source of fileToLines(String fileName)

Description

file To Lines

License

Open Source License

Declaration

public static String[] fileToLines(String fileName) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    public static String[] fileToLines(String fileName) {
        // A list to hold the file's content
        List<String> fileContent = new ArrayList<String>();

        // Reader object for reading the file
        BufferedReader reader = null;

        try {//from w  ww  .  ja  va2 s .  com
            reader = new BufferedReader(new FileReader(fileName)); // Open a reader
            String line = reader.readLine();
            // Go over the rest of the file
            while (line != null) {
                // Read the next line
                fileContent.add(line);
                line = reader.readLine();
            }

        } catch (FileNotFoundException e) {
            System.err.println("ERROR: The file: " + fileName
                    + " is not found.");
            return null;
        } catch (IOException e) {
            System.err.println("ERROR: An IO error occurred.");
            return null;
        } finally {
            // Try to close the file
            try {
                if (reader != null)
                    reader.close();
                else
                    return null;
            } catch (IOException e) {
                System.err.println("ERROR: Could not close the file "
                        + fileName + ".");
            }
        }

        // Convert the list to an array and return the array
        String[] result = new String[fileContent.size()];
        fileContent.toArray(result);
        return result;
    }
}

Related

  1. fileToLines(File file)
  2. fileToLines(String filename)
  3. fileToLines(String filename)
  4. fileToLines(String filePath)