我编写了用Java读取结构化文件的代码,并提取行内容以创建对象(Person类型)。
该文件具有以下结构:[personNumber],[personName],[personAge],例如
0,福尔摩斯,44岁
1,哈利波特,17岁
2,Jack Sparrow,50岁
...
读取文件和提取信息的代码是:
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-objects被正确地添加到我编程的单链表中。这里没问题。
但是,程序也应该能够读取以下格式的文本文件:
#People
0,福尔摩斯,44岁
1,哈利波特,17岁
2,Jack Sparrow,50岁
#Dogs
0,Scooby,10
1,Milou,7
2,伤痕,15岁
有没有办法检查正在读取的行是否包含一个哈希(#)符号,在这种情况下,程序会理解它不是要分割这一行,而只是一个新类别正在启动?这样您就可以决定要从以下行创建哪种类型的对象,例如person og dog对象。为简单起见,类型(Person,Dog)的顺序将始终相同,但每个类别后面的行数将有所不同。因此,我需要帮助确定一行是否包含#-symbol,指示新类别的开始,并且仅从以下行创建对象。
答案 0 :(得分:1)
由于这看起来像家庭作业,我只回答你的第一个问题,让你弄清楚如何在你的程序中使用它。检查您读取的行是否包含哈希符号的方法是:
line = scan.nextLine();
if(line.contains('#')){
// the line had a #
}
else{
//it did not.
}
答案 1 :(得分:1)
或者如果您的#
始终位于字符串的开头:
修改强>:
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);
}
}
答案 2 :(得分:1)
你可以这样做:
String line = null;
String currentType = null;
while((line = rf.readLine()) != null) {
if (line.startsWith("#")) {
currentType = line.substring(1);
continue;
}
split = line.split(",");
if (currentType.equals("People")) {
pnumber = Integer.parseInt(split[0]);
name = split[1];
age = Integer.parseInt(split[2]);
thePerson = new Person(name, age, pnumber);
personList.addLast(thePerson);
} else if (currentType.equals("Dogs")) {
...
Dog dog = new Dog(name,age);
}
}
答案 3 :(得分:1)
首先将readed行分配给变量:
String line = scan.nextLine();
然后将逻辑应用于其值:
if (line.startsWith("#")) {
// check which type of object is declared
} else {
// parse line according to object type
// add object to list
}
另外,我建议对单独类型的对象使用单独的解析器。即DogLineParser,PersonLineParser等等都将实现通用接口。示例界面可能如下所示
public interface LineParser<T> {
T parseLine(String line);
}
示例实现可能如下所示:
public class PersonLineParser extends LineParser<Person> {
@Override
public Person parseLine(String line) {
String[] split = line.split(", ");
pnumber = Integer.parseInt(split[0]);
name = split[1];
age = Integer.parseInt(split[2]);
return new Person(name, age, pnumber);
}
}
答案 4 :(得分:0)
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.startsWith('#')) {
// don't split the
}
else {
// you can split
}
}
scanner.close();