Editando arquivos

5 respostas
B

Olá a todos,

estou precisando editar um arquivo de configuração pelo meu código java mas nao estou conseguindo… toda vez q eu vou escrever usando o PrintWriter ele apaga tudo e depois escreve…

…o que eu preciso é o seguinte, eu tenho esse trecho no arquivo:

Nome: fulano
Email xxxx
Telefone: 111111

e eu queria que ele editasse no arquivo soh pra ficar:

Nome: fulano
Email yyyyy
Telefone: 111111

alguem pode ajudar???

valeus!!!

5 Respostas

lelodois

le o arquivo e grava novamente, controla ele com o cara chamado
String tokenizer… da uma olhada!!!

T

Dica: se você puder mudar o formato do arquivo de configuração para XML ou Properties, é mais fácil depois trabalhar com eles. Vou dar um exemplo para um arquivo Properties:

nome=Joaquim José da Silva Xavier
email=[email removido]
telefone=([telefone removido]

Para ler o arquivo properties, você usa “load”, para gravar o arquivo properties, você usa “save”, e para modificar uma “property”, você usa “setProperty”. Veja a documentação da classe java.util.Properties e veja como é fácil.

B

thingol:
Dica: se você puder mudar o formato do arquivo de configuração para XML ou Properties, é mais fácil depois trabalhar com eles. Vou dar um exemplo para um arquivo Properties:

nome=Joaquim José da Silva Xavier
email=[email removido]
telefone=([telefone removido]

Para ler o arquivo properties, você usa “load”, para gravar o arquivo properties, você usa “save”, e para modificar uma “property”, você usa “setProperty”. Veja a documentação da classe java.util.Properties e veja como é fácil.

hmm, gostei muito dessa api, soh estou tendo problemas na hora de editar o arquivo, pois ele bagunça tudo, eu ja tenho um arquivo de configuracao todo pronto, soh queria editar uma linha nele, tem como fazer isso facil?

T

O properties realmente põe as coisas fora de ordem, porque ele usa internamente um HashMap (não um LinkedHashMap), e ele remove os comentários que você pôs. Eu tenho uma classe que pode ser usada em lugar de java.util.Properties, e que mantém os comentários e a ordem dos dados.

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

/** 
* Esta classe pode ser usada em lugar de java.util.Properties e aceita o mesmo formato de arquivos.
* Entretanto, ela preserva os comentários lidos, assim como a ordem das chaves.
*/
public class Propriedades implements Map {
    /** String "#" */
    private static final String HASH = "#";
    /** Contém o mapa */
    private Map map = new LinkedHashMap();
    /** Contém os defaults */
    private Properties defaults = null;
    /** Formato das chaves */
    private NumberFormat nformat = new DecimalFormat("00000");

    /**
    * Creates an empty property list with no default values.
    */
    public Properties() {
    }

    /**
        * Creates an empty property list with the specified defaults.
        * @param pDefaults the defaults.
        */
    public Properties(Properties pDefaults) {
        defaults = pDefaults;
    }

    /**
        * @see java.util.Map#size()
        */
    public int size() {
        return map.size();
    }

    /**
    * @see java.util.Map#clear()
    */
    public void clear() {
        map.clear();
    }

    /**
    * @see java.util.Map#isEmpty()
    */
    public boolean isEmpty() {
        return map.isEmpty();
    }

    /**
        * @see java.util.Map#containsKey(java.lang.Object)
        */
    public boolean containsKey(Object key) {
        return map.containsKey(key);
    }

    /**
    * @see java.util.Map#containsValue(java.lang.Object)
    */
    public boolean containsValue(Object value) {
        return map.containsValue(value);
    }

    /**
    * @see java.util.Map#values()
    */
    public Collection values() {
        return map.values();
    }

    /**
    * @see java.util.Map#putAll(java.util.Map)
    */
    public void putAll(Map pMap) {
        map.putAll(pMap);
    }

    /**
    * @see java.util.Map#entrySet()
    */
    public Set entrySet() {
        return map.entrySet();
    }

    /**
    * @see java.util.Map#keySet()
    */
    public Set keySet() {
        return map.keySet();
    }

    /**
    * @see java.util.Map#get(java.lang.Object)
    */
    public Object get(Object key) {
        return map.get(key);
    }

    /**
    * @see java.util.Map#remove(java.lang.Object)
    */
    public Object remove(Object key) {
        return map.remove(key);
    }

    /**
    * @see java.util.Map#put(java.lang.Object, java.lang.Object)
    */
    public Object put(Object key, Object value) {
        return map.put(key, value);
    }

    /**
    * @see java.util.Properties#getProperty(java.lang.String)
    */
    public String getProperty(String key) {
        Object obj;
        Properties prop = this;
        
        while (true) {
            obj = prop.get (key);
            if (obj == null && prop.getDefaults() != null) {
                prop = prop.getDefaults();
            } else {
                break;
            }
        }
        
        return (String) obj;
    }

    /**
    * @see java.util.Properties#getProperty(java.lang.String, java.lang.String)
    */
    public String getProperty(String key, String defaultValue) {
        Object obj;
        Properties prop = this;

        while (true) {
            obj = prop.get (key);
            if (obj != null) {
                break;
            } else if (prop.getDefaults() != null) {
                prop = prop.getDefaults();
            } else {
                obj = defaultValue;
                break; 
            }
        }
        return (String) obj;
    }

    /**
    * @return defaults
    */
    Properties getDefaults() { 
        return defaults; 
    }

    /**
    * @see java.util.Properties#propertyNames() 
    */
    public Iterator propertyNames() {
        Set propertyNamesSet = new LinkedHashSet();
        for (Iterator it = map.keySet().iterator(); it.hasNext();) {
            Object key = it.next();
            if (key instanceof String && !((String) key).startsWith(HASH)) {
                propertyNamesSet.add(key);
            }
        }
        if (defaults != null) {
            for (Iterator it = defaults.keySet().iterator(); it.hasNext();) {
                Object key = it.next();
                if (key instanceof String && !((String) key).startsWith(HASH)) {
                    propertyNamesSet.add(key);
                }
            }
        }
        return propertyNamesSet.iterator();
    }

    /**
    * Lê uma lista de propriedades (pares chave=valor) da stream de entrada.
    * A stream deve usar a codificação ISO-8859-1, isto é, 
    * cada byte é um caracter Latin-1.
    * 
    * A sintaxe é ligeiramente diferente de java.util.Properties 
    * e os comentários são preservados na leitura, embora as chaves sejam "#0001", "#0002" etc. para essas linhas.
    * Não se pode usar \ para escapar caracteres, o separador
    * chave/valor é sempre "=" e as linhas não podem ser continuadas.
    * O comentário é sempre começado por "#" ou "!".  Preservamos também as linhas em branco.
    * É efetuado "trim" em todas as linhas, portanto não há como pôr espaços no fim das linhas.
    * Se algum dado for incluído neste "properties", será no final (devido ao
    * uso de LinkedHashMap).
    * Se uma linha não for um par "chave=valor", usando o sinal de igual,
    * ela será armazenada como se fosse um comentário, mas não será possível
    * obtê-la como chave (pois não tem valor).
    * @see java.util.Properties#load(java.io.InputStream) 
    */
    public void load(InputStream inStream)
    throws IOException {
        BufferedReader breader = new BufferedReader (
        new InputStreamReader (inStream, "ISO-8859-1"));
        String line;
        int nComentario = 0;
        int pos;
        map.clear();
        while (true) {
            line = breader.readLine();
            if (line == null) {
                break;
            }
            line = line.trim();
            pos = line.indexOf('=');
            if (line.length() == 0
                    || line.startsWith (HASH) 
                    || line.startsWith ("!") 
                    || pos == -1) {
                map.put(HASH + nformat.format(++nComentario), line);
            } else {
                String key = line.substring(0, pos);
                String value = "";
                if (pos + 1 < line.length()) {
                    value = line.substring (pos + 1);
                }
                map.put(key, value);
            }
        }
        breader.close();
    }
    
    /**
    * @see java.util.Properties#store(java.io.OutputStream, java.lang.String) 
    */
    public void store (OutputStream out, String header) throws IOException {
        PrintWriter pwriter = new PrintWriter (new BufferedWriter (new OutputStreamWriter (out)));
        if (header != null) {
            pwriter.println ("# " + header);
            pwriter.println ("# " + (new Date()).toString());
        }
        for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            if (key.startsWith(HASH)) {
                pwriter.println (value); 
            } else {
                pwriter.println (key + "=" + value);
            }
        }
        pwriter.println();
        pwriter.close();
    }
    
    /**
    * @see java.util.Properties#list(java.io.PrintStream) 
    */
    public void list(PrintStream out) {
        for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            if (!key.startsWith(HASH)) {
                out.println (key + "=" + value);
            }
        }
        out.println();
        out.close();
    }

    /**
    * @see java.util.Properties#list(java.io.PrintWriter) 
    */
    public void list(PrintWriter out) {
        PrintWriter pwriter = out;
        for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            if (!key.startsWith(HASH)) {
                pwriter.println (key + "=" + value);
            }
        }
        pwriter.println();
        pwriter.close();
    }

}
B

vlw :smiley:

Criado 29 de novembro de 2007
Ultima resposta 30 de nov. de 2007
Respostas 5
Participantes 3