从包含多个对象的文本文件创建对象 [英] Creating an object from a text file with multiple objects
问题描述
我需要从txt文件中读取有关汽车的信息,然后将其保存到 ArrayList
。文件中的第一行告诉您文件中有多少辆汽车。
I need to read information about cars from a txt file and then saves it to an ArrayList
. The first line in the file tells you how many cars are within the file.
txt文件如下所示:
The txt file looks like this:
3
2011
Toyota
Corolla
2009
Honda
Civic
2012
Honda
Accord
等等..
我知道如何从a创建一个对象用户输入,但我正在尝试编辑它,所以从文件中读取它。
I know how to create an object from a users input, but I am trying to edit it so reads it from a file.
推荐答案
通常我建议使用 FileReader
,但你说的是您正在重构从用户读取此信息的代码。我想,你正在用扫描仪
读取输入,所以最简单的方法就是更换
Usually I would suggest using a FileReader
, but you said that you are refactoring code which reads this information from the user. I guess, you are reading the input with a Scanner
, so the easiest way to change this is by replacing
Scanner sc = new Scanner(System.in);
这个:
Scanner sc = new Scanner(new File("someFile.txt"));
然后您可以使用扫描仪
:
String fileName = "cars.txt";
List<Car> cars = new ArrayList<>();
try (Scanner sc = new Scanner(new File("someFile.txt"))){
int count = sc.nextInt();
for (int i = 0; i < count; i++) {
int year = sc.nextInt();
String brand = sc.next();
String type = sc.next();
cars.add(new Car(year, brand, type));
}
} catch (IOException e) {
System.err.println("error reading cars from file "+fileName);
e.printStackTrace();
}
还可以使用 sc.hasNext()$在您从
Scanner
中读取之前,c $ c>和 sc.hasNextInt()
,因为您的代码可能会抛出异常如果文件没有有效的内容..
Also use sc.hasNext()
and sc.hasNextInt()
before you read from the Scanner
, since your code might otherwise throw exceptions if the file doesn't have valid content..
您可以在另一个(不同的)中看到 Car
类回答我发布了
You can see the Car
class in another (distinct) answer I posted
这篇关于从包含多个对象的文本文件创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!