Question

In my spring project, one of my service classes has this method to save a file named database.properties in disk:

public void create_properties(String maquina, String usuario, String senha) {
    System.out.println("create_properties");
    Properties props = new Properties();

    props.setProperty("jdbc.Classname", "org.postgresql.Driver");
    props.setProperty("jdbc.url", "jdbc:postgresql://"+maquina+"/horario" );
    props.setProperty("jdbc.user", usuario );
    props.setProperty("jdbc.pass", senha );

    props.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
    props.setProperty("hibernate.show_sql", "false");
    props.setProperty("hibernate.hbm2ddl.auto", "validate");

    FileOutputStream fos;
    try {
        fos = new FileOutputStream( "database.properties" );
        props.store( fos, "propriedades" );
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

My problem is that the property jdbc:url should be something like that:

jdbc:postgresql://localhost:5432/horario

But what is being saved is this:

jdbc\:postgresql\://localhost\:5432/horario

Anyone can tell me how to avoid this backslashes to be included?

Was it helpful?

Solution

It's doing exactly the right thing - you're saving a properties file, which escapes things like colons using backslashes. From the documentation for Properties.store:

Then every entry in this Properties table is written out, one per line. For each entry the key string is written, then an ASCII =, then the associated element string. For the key, all space characters are written with a preceding \ character. For the element, leading space characters, but not embedded or trailing space characters, are written with a preceding \ character. The key and element characters #, !, =, and : are written with a preceding backslash to ensure that they are properly loaded.

If you load the properties file in using Properties.load, you'll get the original string back in the Properties object.

If you don't want to store the value in a properties file, use a Writer and just write the string directly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top