Reputation: 33
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.
The txt file looks like this:
3
2011
Toyota
Corolla
2009
Honda
Civic
2012
Honda
Accord
and so on..
I know how to create an object from a users input, but I am trying to edit it so reads it from a file.
Upvotes: 2
Views: 6120
Reputation: 5841
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);
with this:
Scanner sc = new Scanner(new File("someFile.txt"));
You can then use the Scanner
like that:
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();
}
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..
You can see the Car
class in another (distinct) answer I posted
Upvotes: 3
Reputation: 5841
In case you don't just want to refactor code which used a Scanner
, you can do it with a FileReader
:
String fileName = "cars.txt";
List<Car> cars = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))){
int count = Integer.parseInt(reader.readLine());
for (int i = 0; i < count; i++) {
int year = Integer.parseInt(reader.readLine());
String brand = reader.readLine();
String type = reader.readLine();
cars.add(new Car(year, brand, type));
}
} catch (IOException | NumberFormatException e) {
System.err.println("error reading cars from file "+fileName);
e.printStackTrace();
}
Please note that you might need to do proper error handling in the catch block. Also the reader might return null
as he reaches the end of the file, just in case you want to validate the input coming from the file (which you always should)..
And here is your Car
class:
public class Car {
private final int year;
private final String brand;
private final String type;
public Car(int year, String brand, String type) {
this.year = year;
this.brand = brand;
this.type = type;
}
public int getYear() {
return year;
}
public String getBrand() {
return brand;
}
public String getType() {
return type;
}
}
Upvotes: 2