1
resposta

Desafio: Manipular arquivos

1. Gerar arquivo com mensagem

package DesafioArquivos;

import java.io.FileWriter;
import java.io.IOException;

public class Main {

    public static void main(String[] args) throws IOException {
        FileWriter arq = new FileWriter("arquivo.txt");
        arq.write("Conteúdo a ser gravado no arquivo. ");
        arq.close();
    }
}

2. Desserialização Classe Main:

public class Main {
    public static void main(String[] args) throws IOException {
        Titulo t1 = new Titulo("Homem de ferro", 2008);
        Titulo t2 = new Titulo("Tropa de Elite", 2007);

        Gson gson = new Gson();
        String json1 = gson.toJson(t1);
        String json2 = gson.toJson(t2);

        System.out.println(json1);
        System.out.println(json2);

Titulo:

public class Titulo {
    private String nome;
    private Integer anoLancamento;

    public String getNome() {
        return nome;
    }

    public Integer getAnoLancamento() {
        return anoLancamento;
    }

    public Titulo(String nome, Integer anoLancamento) {
        this.nome = nome;
        this.anoLancamento = anoLancamento;
    }

Saída:

{"nome":"Homem de ferro","anoLancamento":2008}
{"nome":"Tropa de Elite","anoLancamento":2007}

3. SetPrettyPrinting:

Programa igual ao de cima com alteração nessa parte do código apenas:

Gson gson = new GsonBuilder().
                setPrettyPrinting().
                create();

Saída no console:

{
  "nome": "Homem de ferro",
  "anoLancamento": 2008
}
{
  "nome": "Tropa de Elite",
  "anoLancamento": 2007
}

4. Classe veículo:

package DesafioArquivos;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class MainVeiculo {
    public static void main(String[] args) {
        Veiculo carro1 = new Veiculo("Nivus", 2023, "Azul");
        Veiculo carro2 = new Veiculo("Corsa", 2007, "Branco");
        Veiculo carro3 = new Veiculo("HB20", 2010, "Prata");

        Gson gson = new GsonBuilder().
                setPrettyPrinting().
                create();
        String json1 = gson.toJson(carro1);
        String json2 = gson.toJson(carro2);
        String json3 = gson.toJson(carro3);

        System.out.println(json1);
        System.out.println(json2);
        System.out.println(json3);
    }
}

Saída:

{
  "modelo": "Nivus",
  "ano": 2023,
  "cor": "Azul"
}
{
  "modelo": "Corsa",
  "ano": 2007,
  "cor": "Branco"
}
{
  "modelo": "HB20",
  "ano": 2010,
  "cor": "Prata"
}
1 resposta

Parabéns, Paulo!

Muito bem!