我正在尝试从文本文件中读取对象类的参数。该类只需要一个参数int id。其余三个参数是可选的,如果没有提供,则由对象构造函数确定。
文本文件按以下格式生成:
View source
示例:
Inspect element
以下是我目前阅读此格式文件的代码:
`R|G id [volume] [hasESP] [isVegetarian]
int id, int volume, boolean hasESP, boolean isVegitarian
我可以在这里切换使用哪个构造函数,但我无法弄清楚如何找到输入的模式并相应地使用它,所以我没有得到RunTime错误或InvalidArgument错误。任何帮助表示赞赏。
答案 0 :(得分:0)
使用构建器模式,您可以轻松完成。代码示例包含一些lambda。如果你正在使用< jdk8,你可以将lambda转换为常规方法。
class Martian {
private String type;
private int id;
private int volume;
private boolean hasESP;
private boolean isVegitarian;
public Martian(String type, int id, int volume, boolean hasESP,
boolean isVegitarian) {
this.type = type;
this.id = id;
this.volume = volume;
this.hasESP = hasESP;
this.isVegitarian = isVegitarian;
}
public String getType() {
return type;
}
public int getId() {
return id;
}
public int getVolume() {
return volume;
}
public boolean isHasESP() {
return hasESP;
}
public boolean isVegitarian() {
return isVegitarian;
}
public static MartianBuilder builder() {
return new MartianBuilder();
}
static class MartianBuilder {
private String type;
private int id;
private int volume;
private boolean hasESP;
private boolean isVegitarian;
public MartianBuilder type(String type) {
this.type = type;
return this;
}
public MartianBuilder id(int id) {
this.id = id;
return this;
}
public MartianBuilder volume(int volume) {
this.volume = volume;
return this;
}
public MartianBuilder hasESP(boolean hasESP) {
this.hasESP = hasESP;
return this;
}
public MartianBuilder vegitarian(boolean vegitarian) {
isVegitarian = vegitarian;
return this;
}
public Martian build() {
return new Martian(type, id, volume, hasESP, isVegitarian);
}
}
这是您可以使用上面的构建器
的方法public class MartianExample {
void readMartianFile(File file) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
String[] split = line.split(" ");
Martian martian = createMartian(split);
// Decide what to do with read data
}
}
private Martian createMartian(String[] rawData) {
MartianBuilder builder = Martian.builder();
int counter = 0;
// read type
counter = readData(builder::type, counter, rawData);
// read id
counter = readData((idString) -> builder.id(Integer.parseInt(idString)), counter,
rawData);
// read volume
counter = readData((volumeString) -> builder.volume(Integer.parseInt(volumeString)),
counter, rawData);
// read hasESP
counter = readData((hasESPString) -> builder.hasESP(Boolean.parseBoolean(hasESPString)),
counter, rawData);
// read isVegitarian
counter = readData((isVegitarianString) -> builder.vegitarian(Boolean.parseBoolean
(isVegitarianString)), counter, rawData);
return builder.build();
}
private int readData(Consumer<String> consumer, int counter, String[] rawData) {
if (counter < rawData.length) {
consumer.accept(rawData[counter]);
counter++;
}
return counter;
}