提问人:Neku Sakuraba 提问时间:12/10/2022 最后编辑:Mark RotteveelNeku Sakuraba 更新时间:12/10/2022 访问量:28
使用 3 个线程通过 1 个扫描程序读取file.csv的内容,并将内容添加到 ArrayList 中
Using 3 threads to read with 1 scanner the content of a file.csv and adding the content in an ArrayList
问:
我正在用 Java 进行训练,这是我第一次使用它的线程。一个练习要求我从 .cvs 文件中读取,作为奖励,它要求我使用 3 个线程来读取此文件并将信息保存在同一个 ArrayList<CustomClass> 中。我应该有某种问题,因为每个线程都必须从文件中读取唯一的行。
此文件包含以下内容:
Clienti
nome,cognome,tipoMezzo,tipoParcheggio,dataOperazione,Operazione
Paolo,Rossi,cabrio,coperto,07/12/2022 09:00,0
Chiara,Bianchi,moto,aperto,07/12/2022 09:01,0
Abbondazio,Addolorata,4x4,aperto,07/12/2022 09:10,0
Agamennone,Agatangelo,moto,coperto,07/12/2022 09:11,0
Aldebrando,Barachisio,berlina,coperto,07/12/2022 09:12,0
Aldighiero,Barbaziano,moto,aperto,07/12/2022 10:01,0
Aldobrando,Bardomiano,moto,coperto,07/12/2022 10:05,0
Angilberto,Barsanufio,cabrio,aperto,07/12/2022 10:06,0
public class CarParkingImpl implements CarParking {
ArrayList<Cliente> lista;
byte coperto;
byte aperto;
public CarParkingImpl(){
coperto=30;
aperto =50;
lista = new ArrayList<Cliente>();
}
//This function must work with 3 operating Threads that read the same .cvs file and are syncronize to read each one a different line and put the information readed in the ArrayList 'lista'
@Override
public void carParkingFromCSV(String filePath) throws FileNotFoundException {
Scanner scan = new Scanner(new File(filePath));
scan.next();
scan.next();
while(scan.hasNext()){
String[] clientInfo1 = scan.next().split(",");
String[] clientInfo2 = scan.next().split(",");
String[] daySplit = clientInfo1[4].split("/");
String[] timeSplit = clientInfo2[0].split(":");
Calendar tempCalendar = Calendar.getInstance();
tempCalendar.set(Integer.parseInt(daySplit[2]),Integer.parseInt(daySplit[1])-1,Integer.parseInt(daySplit[0]),Integer.parseInt(timeSplit[0]),Integer.parseInt(timeSplit[1]));
Cliente tempClient = new Cliente(clientInfo1[0],clientInfo1[1],clientInfo1[2],clientInfo1[3],tempCalendar,Byte.parseByte(clientInfo2[1]));
try {
carParkingClient(tempClient);
}catch (CarParkingIsFullException e){
System.err.println(e.getMessage());
}
}
scan.close();
}
}
public class Cliente {
String name;
String surname;
String carType;
String parkReq;
Calendar dateOperation;
Byte parkOperation;
public Cliente(String name, String surname, String carType, String parkReq, Calendar dateOperation, Byte parkOperation) {
this.name = name;
this.surname = surname;
this.carType = carType;
this.parkReq = parkReq;
this.dateOperation = dateOperation;
this.parkOperation = parkOperation;
}
}
public class Main {
public static void main(String[] args) throws FileNotFoundException {
String path = "Clienti.csv";
String outPath = "Report.txt";
CarParkingImpl carParking = new CarParkingImpl();
try {
carParking.carParkingFromCSV(path);
carParking.printReport(outPath);
}catch (FileNotFoundException e){
System.err.println(e.getMessage());
}catch (IOException e){
System.err.println(e.getMessage());
}
}
}
答: 暂无答案
评论