XwOku
XwOku

Reputation: 3

How to replaces white spaces from String loaded through properties

I am loading property from file, the property contains path (Windows path) and I need to normalize it to create usable path. The problem is that I can't replace "\".

Here is my test class:

public class PathUtil {

    public static String normalizeEscapeChars(String source) {
        String result = source;

        result = result.replace("\b", "/b");
        result = result.replace("\f", "/f");
        result = result.replace("\n", "/n");
        result = result.replace("\r", "/r");
        result = result.replace("\t", "/t");
        result = result.replace("\\", "/");
        result = result.replace("\"", "/\"");
        result = result.replace("\'", "/'");
        return result;
    }

    public static void main(String[] args) {

        try(FileInputStream input = new FileInputStream("C:\\Users\\Rakieta\\Desktop\\aaa.properties")) {
            Properties prop = new Properties();
            prop.load(input);
            System.out.println(PathUtil.normalizeEscapeChars(prop.getProperty("aaa")));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Here property file:

aaa=Intermix\koza , intermix\trace

Actual output is :

Intermixkoza , intermix/trace

Needed output is :

Intermix/koza , intermix/trace

Any suggestions?

Upvotes: 0

Views: 164

Answers (3)

Izruo
Izruo

Reputation: 2276

The backslash is already interpreted by the java.util.Properties class.

To bypass this, you can extend it and tweak the load(InputStream) method as shown in this answer:

public class PropertiesEx extends Properties {
    public void load(FileInputStream fis) throws IOException {
        Scanner in = new Scanner(fis);
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        while(in.hasNext()) {
            out.write(in.nextLine().replace("\\","\\\\").getBytes());
            out.write("\n".getBytes());
        }

        InputStream is = new ByteArrayInputStream(out.toByteArray());
        super.load(is);
    }
}

Upvotes: 0

user11837257
user11837257

Reputation:

When I copied your code my IDE threw an error saying \k is not a valid escape character. So I removed the whole line.

result = result.replace("\k", "/k");
// I have not seen that escape character (Correct me if I am wrong)

And my output was

aaa=Intermix/koza , intermix/trace

or you try what Connor said that is

result = result.replace("\\k", "/k");
// This code is replacing \k with /k in Intermix\koza. So it is kinda hard coded.

which also gives the same result.

Upvotes: 1

Connor
Connor

Reputation: 364

Use double backslash \\ to escape a backslash in java.

Upvotes: 0

Related Questions