Breaking News
Home / Java / Java Snippets / How to Read Lines from File As String Array?

How to Read Lines from File As String Array?

File Reader as String This snippet shows how read all the lines of a file into an array and finally print the lines. It uses the FileReader to open the file, then reads the each of the lines using the readLine() method and adds the line into the array.

package com.livrona.snippets.io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

/**
 * This snippet shows how read all the lines of a file into and array and
 * finally print the lines.
 * 
 * @author java4learners
 * 
 */
public class LineReader {

	/**
	 * Reads the lines of the file and returns a string array
	 * 
	 * @param fileName
	 * @return
	 */
	public static ArrayList<String> readFileLines(String fileName) {
		BufferedReader rd;
		ArrayList<String> lines = new ArrayList<String>();

		try {
			// open the reader
			rd = new BufferedReader(new FileReader(fileName));
			String line = null;
			// read all the lines till the end
			while ((line = rd.readLine()) != null) {
				lines.add(line);
			}
			rd.close(); // close reader
		} catch (final IOException e) {
			System.out.println("Error reading file");
			throw new RuntimeException(
					"Error reading file : " + e.getMessage(), e);
		}

		return lines;
	}

	/**
	 * Main Test Method
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

		if (args.length != 1) {
			System.out
					.println("Usage: java com.livrona.snippets.io.LineReader <Path to your file>");
			System.exit(0);
		}

		// store args
		String dataFile = args[0];
		System.out.println("File : " + dataFile);

		// read it
		ArrayList<String> lines = readFileLines(dataFile);

		int i = 0;
		// print out the lines
		for (String line : lines) {
			i++;
			System.out.println("Line " + i + ":" + line);
		}

	}
}

 [pb_builder]

Check Also

How to progamatically get the Java version?

Snippet The key here is to use the system property java.version and get minor and …

Leave a Reply