Duvida: Arquivos Properties

15 respostas
malves_info

Tenho a seguinte classe de manipulação de arquivos propeties

public class PropertiesImpl {
	private Properties properties = null;
	private final String PROP_FILE = "properties/config.properties";
	
	public PropertiesImpl() {
		properties = new Properties();
		InputStream in = PropertiesImpl.class.getResourceAsStream(PROP_FILE);
		
		try {
			properties.load(in);
			in.close();
		}  catch (IOException e) {
			e.printStackTrace();
		} 
		
	}
	
	public String getValue(String key){
		return (String)properties.getProperty(key);
	}
	
	public void setValue(String key,String value){
		properties.setProperty(key, value);
		
	}
	
	public static void main(String[] args) {
		PropertiesImpl pImpl = new PropertiesImpl();
		System.out.println(pImpl.getValue("confi_user"));
		pImpl.setValue("confi_user", "false");
		System.out.println(pImpl.getValue("confi_user"));
	}
}

Meu problema esta quando vou setar “config_user” para false, ele não modifica o arquivo properties, continua com o mesmo valor.

:?:

15 Respostas

marcosharbs

tinha usado um properties um tempo atras, vo te passa a classe talvez te ajude:

package Controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import javax.swing.JFormattedTextField;

import sun.tools.jar.resources.jar;

public class Recordes {
	private File file = null;
	private Properties props = null;
	private FileInputStream fis = null;
	private FileOutputStream fos = null;
	
	public Recordes(){
		file = new File("Controller/recordes.properties");
		props = new Properties();
		
	}

	private void loadArquivo(){
		try {
			fis = new FileInputStream(file);
			props.load(fis);
			fis.close();
		} catch (IOException ex) {
			System.out.println(ex.getMessage());
			ex.printStackTrace();
		}
	}


	public void setRecorde(int fase, int record) throws FileNotFoundException, IOException {
		loadArquivo();
		
		String chave = "recorde.fase."+fase;
		Object a = record;
		String valor = a.toString();
		
		fos = new FileOutputStream(file);
		props.setProperty(chave, valor);
		props.store(fos, "Recordes das Fases");
		fos.close();
	}
	
	public int getRecorde(int fase){
		loadArquivo();
		String chave = "recorde.fase."+fase;
		int recorde = Integer.parseInt(props.getProperty(chave));
		return recorde;
	}
	
}
malves_info

Massa… agora ta dando erro no caminho do meu arquivo

java.io.FileNotFoundException: properties\config.properties

minha classe PropertiesImpl esta no pacote projeto.util e meu arquivo properties esta em projeto.util.properties

:shock:

Focao

usa

ResourceBundle rb = ResourceBundle.getBundle("config");

apesar q o ideal era chamar

ApplicationResources.properties

ai ficava assim

ResourceBundle rb = ResourceBundle.getBundle("ApplicationResources");
malves_info

Não entendi a finalidade de ResourceBundle

Focao

era pra ler e ver o cotenudo depois de vc ter salvo

mas pelo que seu caso é esse

Properties properties = new Properties();
    try {
        properties.load(new FileInputStream("filename.properties"));
    } catch (IOException e) {
    }
    
    // Write properties file.
    try {
        properties.store(new FileOutputStream("filename.properties"), null);
    } catch (IOException e) {
    }

senão não vai rolar mesmo

Focao

tem outro exemplo legal nesse link aki do forum

http://www.guj.com.br/posts/list/47947.java

malves_info

Funcionou colocando o caminho assim:

"./bin/meuprojeto/util/properties/config.properties"

Será que vai da problema quando for gerar o jar?? em relação ao diretorio bin?

Focao

acredito q sim

usa assim então

o util/properties é um package né ?

this.getClass().getClassLoader().getResourceAsStream(util/properties/config.properties);

procura ver onde esta o ClassLoader

malves_info

Ae que que esta… se eu for utilizar desta forma ele me retorna um InputStream e quando for utilizar para o OutputStream?? :shock:

Focao

não pode ser URL ?

Focao

vixi agora naum entendi…

sua classe naum é :

InputStream in = PropertiesImpl.class.getResourceAsStream(PROP_FILE);

pode ser assim tbm

InputStream in = PropertiesImpl.class.getClass().getClassLoader().getResourceAsStream(util/properties/config.properties);
malves_info

Quando eu for fazer a leitura do arquivo blz usar:
InputStream in = PropertiesImpl.class.getResourceAsStream(PROP_FILE);

Mas quando eu for fazer alguma alteração no mesmo, vou precisar utilizar FileOutpuStream dae não daria pra utilizar esta linha ae que vc me sugeriu pois PropertiesImpl.class.getResourceAsStream(PROP_FILE) retorna um InputStream.

Parte do metodo que seta minha properties:

public void setValue(String key,String value){
		try {
			
			loadFile();
			fos = new FileOutputStream(new File(??????));// Como informar o caminho aqui!
			properties.setProperty(key, value);
			properties.store(fos, "Update Properties");
			fos.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
Focao
fos = new FileOutputStream(new File(??????));// Como informar o caminho aqui!

se vc deu load no arquivo vc tem o .getAbsoluteFile()

só setar o cara…

em new File(yourFileRead.getAbsoluteFile())

malves_info

Da uma olhadinha como ta minha classe:

public class PropertiesImpl {
	private Properties properties = null;
	private final String PROP_FILE = "./src/meuprojeto/util/properties/config.properties";
	private FileInputStream fis = null;
	private FileOutputStream fos = null;
	private File file = null;
	
	public PropertiesImpl() {
		
		file = new File(PROP_FILE);
		properties = new Properties();
	}
	
	public void loadFile(){
		
		try {
			fis = new FileInputStream(file);
			properties.load(fis);
			fis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public String getValue(String key){
		loadFile();
		return (String)properties.getProperty(key);
	}
	
	public void setValue(String key,String value){
		try {

			loadFile();
			fos = new FileOutputStream(file);
			properties.setProperty(key, value);
			properties.store(fos, "Update Properties");
			fos.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

Como vc pode perceber já informo o caminho do meu arquivo no construtor:

file = new File(PROP_FILE);

Neste caso não poderia utilizar o PropertiesImpl.class.getResourceAsStream(PROP_FILE); pois retorna InputStream. Ae entro no problema mostrado antes que quando for colocar em PROP_FILE o caminho “properties/config.properties” :?

malves_info

HELP?! :frowning:

Criado 27 de janeiro de 2009
Ultima resposta 29 de jan. de 2009
Respostas 15
Participantes 3