我正在使文件读取包含食谱信息的文本文件并对其格式化。为此,我使用了循环,但是阅读部分出现了问题。这是我用作输入的文本文件中一个配方的示例:
"id": 44330
"cuisine": "indian"
"ingredients":
"butter"
"peanut butter"
"chuck"
"curry powder"
"unsalted dry roast peanuts"
"coconut milk"
"brown sugar"
这是我的代码,应该遍历每个元素并将其存储在数组中。我的问题是,我认为我需要仅对成分进行其他排列,因为每个配方样本将具有不同数量的成分。我不确定如何解决此问题或如何编写未指定的数组:
while (currentLine != null) {
String[] RecipeId = currentLine.split("\\s+");
String idName = RecipeId[0];
int id = Integer.valueOf(RecipeId[1]);
String cuisine = RecipeId[2];
String cuisinetype = RecipeId[3];
String[] ingredientsList = currentLine.split("\\s+");
String ingredientOne = ingredientsList[];
recipesFormat.add(new Student(idName, id,cuisine,cuisinetype));
recipesIngredients.add(new Ingredients(ingredientsList));
}
答案 0 :(得分:0)
class Receipt {
private int id;
private String cuisine;
private ArrayList<String> ingredients;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getCuisine() { return cuisine; }
public void setCuisine(String cuisine) { this.cuisine = cuisine; }
public ArrayList<String> getIngredients() { return ingredients; }
public void setIngredients(ArrayList<String> ingredients) { this.ingredients = ingredients; }
}
public List<Receipt> readReceipts() {
List<Receipt> receipts = new ArrayList<>();
Receipt receipt = null;
try (BufferedReader r = new BufferedReader(new FileReader(new File("/path/to/input.txt")))) {
String line;
while((line = r.readLine()) != null) {
// new receipt
if(line.startsWith("\"id\":")) {
// add old
if(receipt != null)
receipts.add(receipt);
receipt = new Receipt();
receipt.setId(Integer.valueOf(line.split(":\\s*")[1].trim()));
line = r.readLine();
receipt.setCuisine(line.split(":\\s*")[1].replaceAll("\"", "").trim());
line = r.readLine(); // skip this line
receipt.setIngredients(new ArrayList<>());
}
else {
receipt.getIngredients().add(line.replaceAll("\"", ""));
}
}
// last fetched receipt
receipts.add(receipt);
} catch (Exception e) {
e.printStackTrace();
}
return receipts;
}