读取Java中的结构化文件 [英] Reading Structured File in Java
问题描述
我已经编写了代码,用于读取Java中的结构化文件,并提取行内容以创建对象(Person类型).
I have written code for reading a structured file in Java, and extracting the line contents to create objects (of type Person).
文件具有以下结构:例如[personNumber],[personName],[personAge]
The file has the following structure: [personNumber], [personName], [personAge], for example
0,福尔摩斯,44岁
0, Sherlock Holmes, 44
1,哈利·波特,17岁
1, Harry Potter, 17
2,杰克·斯派洛(Jack Sparrow),50岁
2, Jack Sparrow, 50
...
读取文件和提取信息的代码是:
The code for reading the file and extracting the information is:
RandomAccessFile rf = new RandomAccessFile(fileName, "rw");
String line;
File myFile = new File(fileName);
scan = new Scanner(myFile);
String[] split;
//Read file
while((line = rf.readLine()) != null) {
split = scan.nextLine().split(", ");
pnumber = Integer.parseInt(split[0]);
name = split[1];
age = Integer.parseInt(split[2]);
thePerson = new Person(name, age, pnumber);
personList.addLast(thePerson);
}
这很好用,并且将Person对象正确添加到了我编写的单链列表中.没问题.
This works well, and the Person-objects are correctly added to a singly linked list that I have programmed. No problems here.
但是,该程序还应该能够读取以下格式的文本文件:
However, the program is also supposed to be able to read a text file of the following format:
#People
0,福尔摩斯,44岁
0, Sherlock Holmes, 44
1,哈利·波特,17岁
1, Harry Potter, 17
2,杰克·斯派洛(Jack Sparrow),50岁
2, Jack Sparrow, 50
#Dogs
0,史酷比,10
1,Milou,7
1, Milou, 7
2,疤痕,15
是否可以检查正在读取的行是否包含井号(#),在这种情况下,程序会了解到它不是要拆分此行,而是只是在开始一个新类别?这样您就可以从以下几行中决定要创建哪种类型的对象,例如,人或狗对象.为简单起见,类型(人,狗)的顺序将始终相同,但是每个类别后面的行数将有所不同.因此,我需要确定行中是否包含#符号,以指示新类别的开始,并且仅从以下几行创建对象.
推荐答案
,或者如果#
始终位于字符串的开头:
or if your #
is always at the beginning of the string:
编辑:
while((line = rf.readLine()) != null) {
if(line.charAt(0)=='#'){
scan.nextLine(); //use it to suit your need..
//alert the program to prepare for new type of object
//do something..
}else {
split = scan.nextLine().split(", ");
pnumber = Integer.parseInt(split[0]);
name = split[1];
age = Integer.parseInt(split[2]);
thePerson = new Person(name, age, pnumber);
personList.addLast(thePerson);
}
}
这篇关于读取Java中的结构化文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!