Backslash (\\) in .proprties file is being ignored by Spring's 'Environment' variable

微笑、不失礼 提交于 2019-12-06 01:02:22

This is a real ugly hack, but you can try and use unicode escape sequence for the symbol "\" which is "\u005c" so instead of string value "abc\xyz" use "abc\u005cxyz". But then again it will translate it to "abc\xyz" and then consider "\" as a start of escape symbol. So if first one doesn't work you can try to replace "abc\\xyz" with "abc\u005c\u005cxyz". See if the first or second option works for you. But in truth, I am surprised that simple escaping "\\" didn't solve your problem. Also if all fails try this "abc\\\\xyz" - this is double escaping.

I used spring 3.1.4-RELEASE and it worked if values in properties file contains '\\'. Like serverName = abc\\xyz

package com.test;   

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration;    
import org.springframework.context.annotation.PropertySource;   
import org.springframework.core.env.Environment;    

@Configuration  
@PropertySource("app.properties")   
public class AppConfig {    

    @Autowired  
    Environment env;

    @Bean   
    public String myBean() {    
        System.out.println(env.getProperty("serverName"));
        return new String(env.getProperty("serverName"));   
    }   
}

Instead of backward slash, I stored them with forward slash in config file.

While reading, I replaced them with double backward slash.

SourcePath=C:/Users/Barani/Documents/SampleData/MyInputFile.txt

    Path currentRelativePath = Paths.get("");
    String filePath = currentRelativePath.toAbsolutePath().toString() + "/config.properties";
    Properties props = new Properties();
    FileInputStream fis = new FileInputStream(filePath);
    props.load(fis);
    sourcePath = props.getProperty("SourcePath").replace("/", "\\\\");

This worked correctly for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!