Access a file using Properties

0

I'm working with a method that takes an object from the Properties class as an argument:

public static void main(String[] args) {
        //Properties props = new Properties();
        Properties props = new Properties();
        props.setProperty("TREINAMENTO.txt", "E:\USER\Documents\Interface");

    }

In the setup method, I have:

public void setUp(Properties props) {


        props.getProperty("TREINAMENTO.txt", "E:\USER\Documents\Interface");

        }

I need to access the file TRAINING.txt, which has the format of a double array, and put it in a training variable [] []. How can I do this? I did not quite understand the operation of the Properties class.

    
asked by anonymous 25.05.2017 / 05:25

1 answer

0

Properties , are configuration files that work with pairs of chave and valor - these keys and values are always Strings .

You use chave to retrieve the valor that you save in this configuration file.

Here's an example of how to read your file (put it in your project folder):

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class LerPropriedades {
    public static void main(String[] args) throws IOException {

        FileInputStream in = new FileInputStream("TREINAMENTO.txt");
        Properties propriedades = new Properties();
        propriedades.load(in);
        in.close();

        for(String chave : propriedades.stringPropertyNames()) {
              String valor = propriedades.getProperty(chave);
              System.out.println(chave + ": " + valor);
            }
    }
}

You can also try creating a properties file to see how it should be structured, like this:

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class SalvarProperties {
    public static void main(String[] args) throws IOException {
        Properties propriedades = new Properties();

        propriedades.setProperty("0", "1.14");
        propriedades.setProperty("1", "132.495");

        FileOutputStream out = new FileOutputStream("TREINAMENTO.txt");
        propriedades.store(out, "---comentario---");
        out.close();
    }
}

If you want to put the information read in array , you can do it in the following way (sorry, I do not know how to do better):

Double meuArray[][] = new Double[10][2];
int counter = 0;

for(String chave : propriedades.stringPropertyNames()) {
    String valor = propriedades.getProperty(chave);
    meuArray[counter][0] = Double.parseDouble(chave);
    meuArray[counter][1] = Double.parseDouble(valor);
    counter++;
}

Only override the for loop of LerPropriedades with this code. I used the following file to test:

#TREINAMENTO
#25/05/2017
0=2.43
1=1.2343
2=15.32
3=80.55
4=532.0
5=943.1
6=9.0
7=3.00038
8=65.12
9=200.01

See More Information

    
25.05.2017 / 06:31