In: Computer Science
Write a JAVA program that reads a text file.
Text file contains three lines.
Place each line in an array bucket location.
Add to the end of the array list.
Print the array.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ReadLinesFromFile {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter file name: ");
File file = new File(in.nextLine()); // create a File object
try {
Scanner fin = new Scanner(file); // open the file for reading
// Just use fin as you would use a typical Scanner object to read in data
ArrayList<String> lines = new ArrayList<String>();
// loop three times
for (int i = 0; i < 3; i++) {
lines.add(fin.nextLine()); // read line from file and add it to lines ArrayList
}
// print ArrayList
for (int i = 0; i < lines.size(); i++) {
System.out.println(lines.get(i));
}
fin.close(); // close the file after using it.
} catch (FileNotFoundException e) {
System.out.println(file.getAbsolutePath() + " is not found!");
}
}
}