Como alterar dado em um arquivo

1 resposta
S

Pessoa xtou com uma dúvida
Não sei como fazer para alterar uma dados específico como por exemplo nome ou idade de um determinado paciente

aí está o código

import java.io.FileInputStream;   
import java.io.FileOutputStream;   
import java.io.ObjectInputStream;   
import java.io.ObjectOutputStream;   
import java.util.ArrayList;   
   
public class Testando {   
       
    public void escrever() throws Exception{   
        ArrayList<Paciente> pacientes = new ArrayList<Paciente>();   
       
        pacientes.add(new Paciente("joão", 10));   
        pacientes.add(new Paciente("maria", 30));   
   
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("arquivo.dat"));   
        out.writeObject(pacientes);   
    }   
       
    public void ler() throws Exception{   
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("arquivo.dat"));   
        ArrayList<Paciente> pacientes = (ArrayList<Paciente>)in.readObject();   
   
        for(Paciente p:pacientes){   
            System.out.println("Nome: " + p.getNome());   
            System.out.println("Idade: " + p.getIdade());   
        }   
    }   
       
    public static void main(String[] args) {   
        Testando t = new Testando();   
        try {   
            t.escrever();   
            t.ler();   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   
}

1 Resposta

ViniGodoy
  1. Leia o arquivo todo num List.
  2. Altere o dado do List;
  3. Salve o List alterado.

Para isso, é melhor alterar seu método escrever e ler para usar a lista por parâmetro.

import java.io.*;
import java.util.*;

public class Teste {
	public void escrever(List&lt;Paciente&gt; pacientes) throws IOException {
		ObjectOutputStream out = null;
		try {
			out = new ObjectOutputStream(new FileOutputStream("arquivo.dat"));
			out.writeObject(pacientes);
			out.flush();
		} catch (IOException e) {
			throw e;
		} finally {
			// Se estiver usando o java 7, use o try with resources.
			if (out != null) try { out.close(); } catch (Exception e) {}
		}
	}

	@SuppressWarnings("unchecked")
	public List&lt;Paciente&gt; ler() throws IOException {
		ObjectInputStream in = null;
		try {
			in = new ObjectInputStream(new FileInputStream("arquivo.dat"));
			return (List&lt;Paciente&gt;) (in.readObject());
		} catch (IOException e) {
			throw e;
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		} finally {
			// Se estiver usando o java 7, use o try with resources.
			if (in != null) try { in.close(); } catch (Exception e) {}
		}

	}

	public static void main(String[] args) {
		Teste t = new Teste();
		try {
			List&lt;Paciente&gt; pacientes = new ArrayList&lt;Paciente&gt;();
			pacientes.add(new Paciente("João", 10));
			pacientes.add(new Paciente("Maria", 15));
			t.escrever(pacientes);
			
			pacientes = t.ler();
			for (Paciente paciente : pacientes)
				System.out.println(paciente);					
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Criado 31 de dezembro de 2011
Ultima resposta 1 de jan. de 2012
Respostas 1
Participantes 2