Java 如何从文件输入中读取类和字段?
我有一个类似以下的文件:Java 如何从文件输入中读取类和字段?,java,arrays,oop,bufferedreader,filereader,Java,Arrays,Oop,Bufferedreader,Filereader,我有一个类似以下的文件: 7 CAT Tabby Jane F 2 7.0 true false DOG Sam Jeff M 7 32.1 true CAT Elsie Kate F 9 9.8 true true DOG Spot Dick M 6 63.4 false BIRD Tweety Dick M 3 0.06 false BIRD Opus Berke
7
CAT Tabby Jane F 2 7.0 true false
DOG Sam Jeff M 7 32.1 true
CAT Elsie Kate F 9 9.8 true true
DOG Spot Dick M 6 63.4 false
BIRD Tweety Dick M 3 0.06 false
BIRD Opus Berkeley M 31 10.3 true
DOG Spot John M 3 42.6 true
> java AnimalHospital pets.data
Tabby owned by Jane: Small Cat, F, Age 2, 7.0 lbs. (not declawed)
Sam owned by Jeff: Medium Dog, M, Age 7, 32.1 lbs.
Elsie owned by Kate: Medium Cat, F, Age 9, 9.8 lbs.
Spot owned by Dick: Large Dog, M, Age 6, 63.4 lbs. (not spayed/neutered)
Tweety owned by Dick: Small Bird, M, Age 3, 0.06 lbs. (not clipped)
Opus owned by Berkeley: Large Bird, M, Age 31, 10.3 lbs.
Spot owned by John: Medium Dog, M, Age 3, 42.6 lbs.
我的文件的第一列代表类,下面的列代表各个类的变量/字段值。我想以某种方式阅读这些行,以便我的读者识别出第一列是类,第二列是名称变量,第三列是所有者变量,第四列是名称的性别(pet)等等。
以下是变量(以防您需要强烈的想法):
因此,当我以以下方式读取文件输入时:
public void readData() throws Exception{
BufferedReader filename = new BufferedReader(new FileReader("pets.txt"));
String str;
List<String> list = new ArrayList<String>();
while((str = filename.readLine()) != null){
String[] temp = str.split("\\s+",2);
list.add(temp[1]);
}
pets = list.toArray(new String[6]);
for (String x: pets) {
System.out.println(x);
}
}
我希望我的问题有足够的信息来澄清我的核心问题。我从你的问题中了解到,基本上你必须对类名和值进行映射。你可以用这个地图 因为您知道第一列是宠物类,第二列是姓名,第三列是性别等,所以在基于“”拆分整行后,您可以使用Map m,以便:
m.put("class",temp[0]);
m.put("name",temp[1]);
等等
返回类型将是Map
希望这对您有所帮助。如果您希望避免反射,并且假设您事先知道所有的类,并且使用java8,那么您可以编写如下switch语句:
Animal animal;
switch (tmp[0]) {
case "CAT":
animal = new Cat();
break;
case "DOG":
animal = new Dog();
break;
// etc etc
default:
throw new RuntimeException("Unknown animal:" + tmp[0]);
}
使用BufferedReader无法完成此操作。BufferedReader没有此功能。您必须对其进行分析。您需要使用类似于
Class.forName()的构造。
。这种技术叫做反射。@Evangey它说反射是一种功能强大的工具,建议只有了解基本功能的高级用户才能使用。你能推荐像我这样的初学者可以使用的其他技术吗?我真的很想学习,而不是仅仅使用高级API类来实现这个目的。重新反射-的确,反射是强大的,尽管使用强大的工具没有什么错,不尝试也无法学习它们。。。
Animal animal;
switch (tmp[0]) {
case "CAT":
animal = new Cat();
break;
case "DOG":
animal = new Dog();
break;
// etc etc
default:
throw new RuntimeException("Unknown animal:" + tmp[0]);
}