Quantcast
Channel: Developer Feed - Snippet
Viewing all articles
Browse latest Browse all 178

How to Read Lines from File As String Array?

$
0
0

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 arrary.

<!--break-->


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
*
*/

publicclass LineReader {

/**
* Reads the lines of the file and returns a string array
*
* @param fileName
* @return
*/

publicstatic 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");
thrownew RuntimeException(
"Error reading file : "+ e.getMessage(), e);
}

return lines;
}

/**
* Main Test Method
*
* @param args
*/

publicstaticvoid 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);
}

}
}




Viewing all articles
Browse latest Browse all 178

Trending Articles