Дан файл. В нём построчно записаны поля в соответствующем порядке. Нужно считать поля файла, создав объекты и затем записать эти объекты в массив. Почему-то при записи объектов считываю их правильно, но записывается только последний. Что делать.
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
String file_directory, file_name;
int changer = -1;
System.out.println("Enter amount of objects you want to add");
int n = Typetester.SetInt();
ArrayList<Route> arr = new ArrayList<>();
while (changer != 0) {
System.out.println("1 - Add object to file");
System.out.println("2 - Add objects to array");
System.out.println("0 - Exit");
changer = Typetester.SetInt();
switch (changer) {
case 1:
new_object_to_file(file1);
break;
case 2:
add_to_array(file1, n, arr);
break;
case 0:
changer = 0;
System.out.println("Exiting program...");
System.exit(0);
}
}
}
public static void add_to_array(File file1, int n, ArrayList<Route> arr1) {
int curr_number, curr_price;
String curr_last_station, curr_time, buff;
try (Scanner fl = new Scanner(file1)){
int j = 0;
while(j != n) {
curr_number = fl.nextInt();
buff = fl.nextLine();
curr_last_station = fl.nextLine();
curr_time = fl.nextLine();
curr_price = fl.nextInt();
buff = fl.nextLine();
arr1.add(new Route(curr_number, curr_last_station, curr_time, curr_price));
j++;
}
}
catch(FileNotFoundException ex){
System.out.println("File doesn't exist");
}
for(int i = 0; i < n; i++){
arr1.get(i).show();
}
}
public static void show_array(ArrayList<Route> arr, int n){
for(int i = 0; i < n; i++){
arr.get(i).show();
}
}
public class Route{
public static int number;
public static String last_station;
public static String time_of_departure;
public static int price;
Route(int Number, String Last_station, String Time_of_departure,
int Price){
this.number = Number;
this.last_station = Last_station;
this.time_of_departure = Time_of_departure;
this.price = Price;
}
public void add_to_file(File file1){
try (FileWriter writer = new FileWriter(file1, true)) {
writer.write(number + "\r\n");
writer.write(last_station + "\r\n");
writer.write(time_of_departure + "\r\n");
writer.write(price + "\r\n");
writer.flush();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
public void show(){
System.out.println("Number: " + this.number);
System.out.println("Last Station: " + this.last_station);
System.out.println("Time of Departure: " + this.time_of_departure);
System.out.println("Price: " + this.price);
}
public int getNumber() {
return number;
}
public void clear(){
this.number = 0;
this.last_station = null;
this.time_of_departure = null;
this.price = 0;
}
}