Josiah Wu Josiah Wu - 8 months ago 51
Java Question

how to read text file orderly in Java?

I know how to read a text file, but I don't know how to read it orderly. For instance, how to read this" Tosca|Giacomo Puccini|1900|Rome|Puccini’s melodrama about a volatile diva, a sadistic police chief, and an idealistic artist|"? Different information is separated by | , and I want them to display on different JLabel.

I did this

while((line = bufferedReader.readLine()) != null) {

What else should I do in the while loop?


You need to split the string data using split function and put it to an array of string to get your desired data in group. Example: str = "10 | Patrick | 10-10-1996"

To store the data above and put it nicely into the database, you can split the string and store it to a class named 'Person' that contains data such as name,id, and birthday.

class Person{
    private int id;
    private String name;
    private String birthday;
    public Person(int id, String name, String birthday){
        //some setter code here

    //some getter code here

Then you can split each line of data you read in the text file.

while((line = bufferedReader.readLine()) != null) {
            String data[] = line.split("|")
            // data[0] to get the id you need
            // data[1] to get the name
            // data[2] to get the birthday