【问题标题】:How can I get a specific value from txt file in java?如何从 java 中的 txt 文件中获取特定值?
【发布时间】:2022-03-18 03:04:41
【问题描述】:

我有两个 .txt 文件:

  1. mothers.txt (IdNum, name, age) 例如:6, Emily, 34
  2. children.txt (num, sex(boy/girl), name, dateOfBirth, weight, height, IdnumOfMother) 例如:1 b Jackson 1999-10-15 3450 55 6

我唯一能做的就是把它们全部写成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();

我要找到最高的男孩,最重的女孩,大多数孩子出生的那一天

你能帮帮我吗?这是我第一次使用 .txt 文件。 提前谢谢你。

【问题讨论】:

  • 从您的代码中可以明显看出(尽管不是您的示例),您似乎有一个 CSV。您也可以考虑添加该标签。
  • 我不知道您对 Java 和一般编码有多陌生,所以您应该这样做:正如其他人已经指出的那样,您似乎拥有 CSV 而不是纯txt 文件,您可以使用库来解析所有内容,并且可以获取有关整洁数组中任何列的信息,然后您应该能够回答库为您创建的对象中的所有问题。

标签: java csv file txt reader


【解决方案1】:

您的问题需要根据不同的条件搜索文件以获得所需的属性值。使用 Java 编写该任务的代码非常适用。

使用 Java 的开源包 SPL 可以很方便地完成这项工作。 SPL 只需要几行代码:

| |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 提供 JDBC 驱动程序供 Java 调用。只需将上述 SPL 脚本存储为 spicify.splx 并在调用存储过程时在 Java 中调用它:

…

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

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

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

st.execute();

…

您还可以使用 SPL 通过外键方便地关联两个文件。例如,要查找最高男婴母亲的年龄和最重女婴母亲的年龄,SPL 有以下代码:

| |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|

查看SPL source code

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 1970-01-01
    • 2011-05-20
    • 2014-06-03
    • 1970-01-01
    • 2018-06-28
    • 2022-01-18
    • 1970-01-01
    相关资源
    最近更新 更多