Accessing a file using Properties

I am working with a method that takes as argument an object of the Properties Class:

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 training file.txt, which has the format of a double array, and put it in a training variable [] []. How can I do that? I didn't quite understand how the properties class works.

Author: donut, 2017-05-25

1 answers

Properties, These 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 you save in that 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 put the information read in a array, you can do 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++;
}

Just replace the loop for 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 here more information

 0
Author: Daniel, 2017-05-25 05:02:03