Java analogous to Python os.path.expanduser / os.path.expandvars
Is there such a thing as Python's os.path.expanduser
and os.path.expandvars
(docume开发者_如何学Cntation) in Java?
If not, is there a library somewhere that does this?
It's a shame that Java doesn't come with "batteries included" :(
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Path {
static Pattern pv=Pattern.compile("\\$\\{(\\w+)\\}");
/*
* os.path.expanduser
*/
public static String expanduser(String path) {
String user=System.getProperty("user.home");
return path.replaceFirst("~", user);
}//expanduser
/*
* os.path.expandvars
*/
public static String expandvars(String path) {
String result=new String(path);
Matcher m=pv.matcher(path);
while(m.find()) {
String var=m.group(1);
String value=System.getenv(var);
if (value!=null)
result=result.replace("${"+var+"}", value);
}
return result;
}//expandvars
}///
I don't know of anything that does exactly what you want, but you can get a user's home dir with System.getProperty("user.home")
and you can resolve environment variables using System.getenv(String name).
精彩评论