拆分文件中的信息并阅读它们

时间:2015-11-21 23:36:36

标签: java file parsing constructor

我有一个文本文件:

Jim Webb 27 Axelrod Street
Hillary Sanders 92 California Street
Bernie Trudeau 46 Pot Street
Barack Bush 883 White Ave
Mary Warren 736 Something Rd
Donald Crump 65 Debate Street

我需要解析一个人,名字,姓氏和地址(姓氏后的信息)。

这是我的尝试:

public Parse() {
        parseFiles();
    }

    void parseFiles() {
        try {
            File file = new File("school.txt");
            Scanner sc = new Scanner(file);

            while (sc.hasNextLine()) {
                String s = sc.nextLine();
                String[] splited = s.split("\\s+");
                for (int i = 0; i < splited.length; i++) {
                    System.out.println(splited[i]);
                }
            }

        } catch (FileNotFoundException e) {
            System.out.println("File not found\n");
        }

    }

}

不幸的是,我的方法按空格解析每一行空间,这适用于名字和姓氏,但不适用于地址,因为我希望地址是一整个字符串,而不是一串字符串由空格分隔。

例如,我有一个这样的学生班:

public Student(String name, String lastName, String address) {
this.name = name
//etc... 
}

我想每次初始化一个学生(在每一行阅读之后),但是通过我的实现,我只能为人名和姓做,我将如何分别解析整个地址?然后可以调用学生构造函数。

2 个答案:

答案 0 :(得分:4)

您可以使用.next()获取名字和姓氏,然后使用.nextLine()来获取其余部分,如下所示:

String firstName = sc.next();
String lastName = sc.next();
String address = sc.nextLine();

答案 1 :(得分:2)

假设文件结构将从不更改,则地址将始终位于最后两个位置。在if

中添加for条款
for (int i = 0; i < splited.length; i++) {
    if(i >= (splited.length - 2)) {
        System.out.println(splited[i] + " " + splited[i + 1]);
        break;
    } else
        System.out.println(splited[i]);
}

您可以进一步调整for循环以在(splited.length - 2)位置之前停止:

for (int i = 0; i < (splited.length - 2); i++) {
    System.out.println(splited[i]);
}
System.out.println(splited[splited.length - 2] + " " + splited[splited.length - 1]);