J
J
javax2011-01-04 18:47:22
Java
javax, 2011-01-04 18:47:22

Expand environment variables in a string?

How to convert a string like
"Tralala ~/bin;${JAVA_HOME} trululu"
to
"Tralala /home/lenochka/bin;/bin/java trululu" in Java
- i.e. expand all environment variables and tilde that are inside the string.
Googled - I did not find the necessary libraries :(

Answer the question

In order to leave comments, you need to log in

4 answer(s)
R
relgames, 2011-01-07
@relgames

The task is basically divided into 3 parts
1) extracting variable names
2) getting their values
​​3) assembling a string
For 1, you can use regular expressions, or some kind of template-engine (expensive).
For 2, you can use System.getenv
For 3, again, regular expressions or a simple replacement via String.replace

V
Viktor Kuznetsov, 2011-01-04
@janitor

You can use System.getProperty(String Property);
You just have to make a match for the function parameter for all environment variables. For example:
'JAVA_HOME': 'java.home',
'~': 'user.home'
I just started learning Java myself, so I don't know, maybe there is a better option

1
1nd1go, 2011-01-04
@1nd1go

try to do System.exec("$JAVA_HOME").getOutputStream() and read it into a string. Get what the variable contains

C
cthulhudx, 2015-12-25
@cthulhudx

Map<String, String> env = System.getenv();
        for (String envName : env.keySet()) {
            System.out.format("%s=%s%n", envName, env.get(envName));
        }

->
JAVA_HOME=/usr/lib/jvm/java-8-oracle
XDG_CONFIG_DIRS=/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg
XFILESEARCHPATH=/usr/dt/app-defaults/%L/Dt
XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat0
GNOME_KEYRING_CONTROL=
LANG=ru_RU.UTF-8
XDG_SESSION_TYPE=x11
XDG_SESSION_ID=c1
DISPLAY=:0
GDM_LANG=ru_RU
XDG_GREETER_DATA_DIR=/var/lib/lightdm-data/quadra
UPSTART_EVENTS=xsession started
SESSION=ubuntu
DESKTOP_SESSION=ubuntu
GPG_AGENT_INFO=/run/user/1000/keyring/gpg:0:1
...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question