In: Computer Science
Computer Science - Java Programming
How do you read a text file and store three different pieces of information in the database when the given text file contains this info.:
12345 Computer Science Bob Stone
23456 Art James G. Ocean?
These are written in the format as
ID Class Name.
I was going to take the three different pieces of information by separating them by spaces, but the number of spaces is random and I don't know how to adjust it accordingly.
How should I do this? Is it even possible?
Answer:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class FileReader {
public static void main(String[] args) {
try {
// creating file
object here
File fileObj =
new File("test-data.txt");
// creating
scanner object to read file line by line
Scanner scanner
= new Scanner(fileObj);
// priting
header line of table
System.out.format("%6s| %10s| %16s", "Id", "Class", "Name");
System.out.println("\n--------------------------------------");
// iteratng
while to read file data
while
(scanner.hasNextLine()) {
// reading line
String line = scanner.nextLine();
// spliting line by providing regex and limit to
split function
// "\\s" is regex for whitespace and 3 is limit,
so this split the string upto 3 whitespaces
String data[] = line.split("\\s", 3);
// printng a data into table format using format
spacifier
System.out.format("%6s| %10s| %16s", data[0],
data[1], data[2]);
System.out.println("");
}
// closing
scanner object
scanner.close();
} catch (FileNotFoundException e)
{
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output: