Streams and writers 2
Wed May 29 2024 09:16:38 GMT+0000 (Coordinated Universal Time)
Saved by @exam123
Client.java
public class Client {
private Integer clientId;
private String name;
private String email;
private String phoneNumber;
private String country;
public Client(Integer clientId, String name, String email, String phoneNumber, String country) {
this.clientId = clientId;
this.name = name;
this.email = email;
this.phoneNumber = phoneNumber;
this.country = country;
}
// Getters and Setters
public Integer getClientId() {
return clientId;
}
public void setClientId(Integer clientId) {
this.clientId = clientId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
// Override toString method for CSV format
@Override
public String toString() {
return clientId + "," + name + "," + email + "," + phoneNumber + "," + country;
}
}
Main.java**
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
FileUtility fileUtility = new FileUtility();
Client[] clients = fileUtility.readFileData(br);
Arrays.sort(clients, Comparator.comparing(Client::getClientId));
fileUtility.writeDataToFile(clients);
System.out.println("Output file generated successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileUtility.java**
import java.io.*;
import java.util.*;
public class FileUtility {
public Client[] readFileData(BufferedReader br) throws IOException {
List<Client> clientList = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(",");
Integer clientId = Integer.parseInt(parts[0].trim());
String name = parts[1].trim();
String email = parts[2].trim();
String phoneNumber = parts[3].trim();
String country = parts[4].trim();
clientList.add(new Client(clientId, name, email, phoneNumber, country));
}
br.close();
return clientList.toArray(new Client[0]);
}
public void writeDataToFile(Client[] clientArray) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.csv"))) {
for (Client client : clientArray) {
writer.write(client.toString());
writer.newLine();
}
}
}
}



Comments