Generate File :
public class GenerateFile {
public static void generateFile(Address address){
try(BufferedWriter bufferedWriter = new BufferedWriter( new FileWriter(address.cep()))){
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
bufferedWriter.write(writer.writeValueAsString(address));
}catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Address :
public record Address(
String cep,
String logradouro,
String complemento,
String unidade,
String bairro,
String localidade,
String uf,
String estado,
String regiao,
String ibge,
String gia,
String ddd,
String siafi) {
}
SearchCep :
public class SearchCep {
public static Address search(String cep) {
validaCep(cep);
String apiUrl = "https://viacep.com.br/ws/"+cep+"/json/";
try(HttpClient client = HttpClient.newHttpClient()){
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(apiUrl))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(response.body(),Address.class);
}catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
public static boolean validaCep(String cep){
Pattern pattern = Pattern.compile("\\D");
Matcher matcher = pattern.matcher(cep);
if(matcher.find()){
throw new IllegalArgumentException("The CEP input accepts only numbers");
}else if(cep.length()>8){
throw new IllegalArgumentException("The CEP must contain exactly 8 numbers");
}
return true;
}
Main :
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try{
System.out.println("Enter your cep : ");
String cep = scanner.nextLine();
Address address = SearchCep.search(cep);
GenerateFile.generateFile(address);
} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
}
}