不需要的反斜杠添加到java方法保存的文件中 [英] Unwanted backslash added to file saved by java method

查看:264
本文介绍了不需要的反斜杠添加到java方法保存的文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的spring项目中,我的一个服务类使用此方法将名为database.properties的文件保存在磁盘中:

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();
    }
}

我的问题是属性jdbc:url应该是这样的:

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

jdbc:postgresql://localhost:5432/horario

但是保存的是这个

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

任何人都可以告诉我如何避免包含反斜杠吗?

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

推荐答案

这是完全正确的事情-您正在保存一个 properties 文件,该文件使用反斜杠转义了诸如冒号之类的内容.从 Properties.store 的文档:

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:

然后,将写出此属性表中的每个条目,每行一个.对于每个条目,将写入密钥字符串,然后是ASCII =,然后是关联的元素字符串.对于键,所有空格字符都以前面的\字符书写.对于该元素,前导空格字符(而不是嵌入空格字符或尾随空格字符)使用前一个\字符编写.键和元素字符#,!,=和:前面写有反斜杠,以确保它们已正确加载.

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.

如果使用Properties.load加载属性文件,则会在Properties对象中获得原始字符串.

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

如果您不想将值存储在属性文件中,请使用Writer并直接将字符串写入.

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

这篇关于不需要的反斜杠添加到java方法保存的文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆