How Can I Get a Specific Value from txt File in Java

Question

Source: https://stackoverflow.com/questions/70226212/how-can-i-get-a-specific-value-from-txt-file-in-java

I have two .txt files:

1.     mothers.txt (IdNum, name, age). For example: 6, Emily, 34

2.     children.txt (num, sex(boy/girl), name, dateOfBirth, weight, height, IdnumOfMother). For example: 1 b Jackson 1999-10-15 3450 55 6

The only thing I can do is to write them all by String[].

String child = "children.txt";

        BufferedReader reader = null;

        String line = "";

 

        reader = new BufferedReader(new FileReader(child));

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

 

            String[] row = line.split(",");

 

            for (String x : row){

                System.out.printf("%-10s", x);

            }

            System.out.println();

        }

        reader.close();

I have to find the tallest boy, the heaviest girl, and the day when most children were born.

Can you help me? It's my first time with .txt files. Thank you in advance.

Answer

Your problem requires searching files according to different conditions to get the desired attribute values. Using Java to code the task is narrowly applicable.

It is convenient to get this done using SPL, Java’s open-source package. SPL only needs a few lines of code:

A

1

=file("children.txt").import@ct()

2

=A1.select(sex=="b").maxp@a(height).(dateOfBirth)

3

=A1.select(sex=="g").maxp@a(weight).(dateOfBirth)

4

return A2,A3

 

SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as spicify.splx and invoke it in Java as you call a stored procedure:

 

Class.forName("com.esproc.jdbc.InternalDriver");

con = DriverManager.getConnection("jdbc:esproc:local://");

st = con.prepareCall("call spicify()");

st.execute();

You can also use SPL to conveniently associate two files by foreign key. To find the age of the tallest baby boy’s mother and the age of the heaviest baby girl’s mother, for example, SPL has the following code:

A

1

=file("mothers.txt").import@ct()

2

=file("children.txt").import@ct().switch(IdnumOfMother,A1:IdNum)

3

=A2.select(sex=="b").maxp@a(height).(IdnumOfMother.age)

4

=A2.select(sex=="g").maxp@a(weight).(IdnumOfMother.age)

5

return A3,A4

View SPL source code.