In: Computer Science
Write a java code segment to declare an array of size 10 of type String and read data for them from a file, prompt user for the file name. Data is stored in a file with 1 string per line.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
String[] lines = new String[10];
System.out.print("Enter file name: ");
Scanner in = new Scanner(System.in);
int numLines = 0;
File file = new File(in.nextLine()); // read a file and create a file.
try {
Scanner fin = new Scanner(file); // create a scanner to read from file
while (fin.hasNextLine() && numLines < lines.length) { // read each line from file
lines[numLines++] = fin.nextLine();
}
// print array
System.out.println("Lines read from the file are");
for (int i = 0; i < numLines; i++) {
System.out.println(lines[i]);
}
fin.close(); // close file.
} catch (FileNotFoundException e) {
System.out.println("Error. " + file.getAbsolutePath() + " does not exists!"); // if file does not exist, report an error
}
}
}