How To - Read TextFile into Array
Description:
These are many ways to read a text-file into an array.
myTextFile.txt
2014-12-01 Durban to Cape Town 2014-12-04 Port Elizabeth to Durban 2014-12-05 Durban to Kimberley 2014-12-05 Durban to Potchefstroom 2014-12-07 Potchefstroom to Durban 2014-12-09 Durban to Bloemfontein
Most Common Method: Using Scanner & String[] Arrays
This is the most used method, as it is used to easily split the contents of a Text File line by line into a String Array:
public void readTextFile(String fileName) throws FileNotFoundException {
String content = "";
Scanner myTextFile = new Scanner(new FileReader(fileName)).useDelimiter(",\\s*");
while (myTextFile.hasNext()) {
// All the contents of the Text File are added to the "content variable
content = myTextFile.next();
}
myTextFile.close();
// Creating a String Array to store each individual line
String[] lines = content.split("\n");
/* The contents of the text file stored in the String variable "contents"
is being split line by line into the String Array.
The contents are being split into lines using the String.split(Regex) method, where "Regex" stands for
any given "regular expression" and "String" is your String variable
The String.split(Regex) method splits this string around matches of the given regular expression.
*/
}
Alternate Method: Using Scanner & ArrayLists
Here is the code for this method:
public class ReadTextFile {
public static void main(String[] args) throws IOException {
// TODO code application logic here
// create String variable to store each line
String line = "";
// create Scanner
Scanner myFile = new Scanner(new FileReader("myTextFile.txt")).useDelimiter(",\\s*");
ArrayList<String> tempArray = new ArrayList<String>(); // Using ArrayList to temporary store values.
//ArrayLists are better suited than Arrays for this as you don't have to declare memory space for them.
// while loop
while (myFile.hasNext()) {
// find next line
line = myFile.next();
tempArray.add(line); // Adding line to ArrayList
}
myFile.close();
//Converting ArrayList to Array using .toArray() Method
String[] myStringArray = tempArray.toArray(new String[0]);
for (String outputLine : myStrinArray) {
System.out.print(outputLine);
}
}
}
Advertisements